简述
c#定义数组或向量传递指针参数,c++算法向数组指针输出参数数据
内容
[System.Runtime.InteropServices.DllImport(@"NativeLib.dll",
EntryPoint = "MthCopy",
CharSet = System.Runtime.InteropServices.CharSet.Ansi,
CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
private static extern int MthCopy(byte[] Source, ref IntPtr Trans, int Len);
[System.Runtime.InteropServices.DllImport(@"NativeLib.dll",
EntryPoint = "MthPtrArrayFree",
CharSet = System.Runtime.InteropServices.CharSet.Ansi,
CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
private static extern int MthPtrArrayFree(IntPtr PtrArray);
调用代码:
int Len = 4;
byte[] Source = new byte[] { 1, 2, 3, 4 };
IntPtr Trans = IntPtr.Zero;
MthCopy(Source, ref Trans, 4);
byte[] TransArr = new byte[Len];
//复制或者用unsafe直接访问指针
System.Runtime.InteropServices.Marshal.Copy(Trans, TransArr, 0, TransArr.Length);
MthPtrArrayFree(Trans);
c++ dll
extern "C" __declspec(dllexport) int__stdcall MthCopy(BYTE *Source, BYTE *&Trans, int Len);
extern "C" __declspec(dllexport) int__stdcall MthPtrArrayFree(void *PtrArray);
int MthCopy(BYTE *Source, BYTE *&Trans, int Len)
{
Trans = new BYTE[Len];
memcpy_s(Source, Len, Trans, Len);
}
int MthPtrArrayFree(void *PtrArray)
{
if (PtrArray)
{
delete[] PtrArray;
PtrArray = nullptr;
}
return 0;
}
c++ dll例2
extern "C" __declspec(dllexport) int__stdcall MthCopy(BYTE *Source, BYTE *&Trans, int Len);
extern "C" __declspec(dllexport) int__stdcall MthPtrArrayFree(void *PtrArray);
int MthCopy(BYTE *Source, BYTE *&Trans, int Len)
{
Trans = new BYTE[Len];
memcpy_s(Source, Len, Trans, Len);
}
int MthPtrArrayFree(void *PtrArray)
{
if (PtrArray)
{
delete[] PtrArray;
PtrArray = nullptr;
}
return 0;
}