C#调用C/C++动态库的参数传递---数组指针的传递

C/C++ CODE:

extern "C" __declspec(dllexport) void Test(int* ptr_int, unsigned char* ptr_byte);

...

extern "C" __declspec(dllexport) void Test(int* ptr_int, unsigned char* ptr_byte)
{
for(int i = 0; i < 10; i++)
{
TRACE(L"%d ",ptr_int[i]);
}
for(int i = 0; i < 10; i++)
{
TRACE(L"0x%02X ",ptr_byte[i]);
}

}

//注:TRACE函数是MFC里面的一个调试函数,非MFC下的不能使用

//不过,可以使用下面的函数来替代:

bool _trace(TCHAR *format, ...)
{
TCHAR buffer[1000];
va_list argptr;
va_start(argptr, format);
wvsprintf(buffer, format, argptr);
va_end(argptr);
OutputDebugString(buffer);
return true;
}


C#
[DllImport("XXXX.dll", EntryPoint = "Test", CallingConvention = CallingConvention.Cdecl)]
public static extern void Test(IntPtr ptr_int,IntPtr ptr_byte);
...
byte[] byte_buffer = new byte[10]{0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A};
GCHandle hObject = GCHandle.Alloc(byte_buffer, GCHandleType.Pinned);
IntPtr ptr_byte = hObject.AddrOfPinnedObject();
int[] int_buffer = new int[10]{11,22,33,44,55,66,77,88,99,100};
hObject = GCHandle.Alloc(int_buffer, GCHandleType.Pinned);
IntPtr ptr_int = hObject.AddrOfPinnedObject();

Test(ptr_int, ptr_byte);


有了C#向C++传递指针的办法,那么C#,C++的交互就方便很多了。

你可能感兴趣的:(C/C++交互,C#)