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; i14: {
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