Manage C++包装Native C++类的例子

Native C++
 
   1:  #include 
  
  
   2:   
   3:  class CPPClass
   4:  {
   5:  public:
   6:    CPPClass(void) {};
   7:  public:
   8:    ~CPPClass(void) {};
   9:   
  10:    void produceByteArray(unsigned char* array, int length)
  11:    {
  12:      printf("CPPClass: Producing %i elements/n", length);
  13:      for (int i=0; i
  
  

  
   
   
  14:      {
  15:        array[i] = i*2;
  16:      }
  17:    }
  18:  };

包装后的Managed C++

   1:  using namespace System;
   2:  #include "CPPClass.h"
   3:   
   4:  namespace SimpleInterop
   5:  {
   6:    public ref class ManagedWrapperClass
   7:    {
   8:    public:
   9:      ManagedWrapperClass(void) { _pCPPClass = new CPPClass(); };
  10:   
  11:      // Wrapper method for the produceByteArray C++ method
  12:      // array
   
   
    
    ^ represents a managed byte array
   
   
  13:      void produceByteArray(array<byte>^ data)
  14:      {
  15:        // The following line fixes the managed array to a pointer. This avoids
  16:        // that the address of the array is changed by the garbage collector.
  17:        pin_ptr<byte> p = &data[0];
  18:        _pCPPClass->produceByteArray(p, data->Length);
  19:      }
  20:   
  21:    private:
  22:      CPPClass* _pCPPClass;
  23:    };
  24:  }

在C#中使用

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Text;
   4:   
   5:  namespace SimpleInterop
   6:  {
   7:    class Program
   8:    {
   9:      static void Main(string[] args)
  10:      {
  11:        ManagedWrapperClass CPPClass = new ManagedWrapperClass();
  12:   
  13:        // Test the produceByteArray method
  14:        byte[] data = new byte[10];
  15:        CPPClass.produceByteArray(data);
  16:        foreach (byte element in data) { Console.WriteLine(element); }
  17:   
  18:        Console.WriteLine("Press return");
  19:        Console.Read();
  20:      }
  21:    }
  22:  }

原帖:http://blog.naiznoiz.com/2008/01/cc-interop-a-simple-example

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值