mX6*_*X64 0 c# c++ extern intptr
我有一个c ++ dll,它有一些外部功能.它看起来像这样
//C++ Code
void GetData(byte * pData)
{
byte a[] = {3,2,1};
pData = a;
}
Run Code Online (Sandbox Code Playgroud)
我在C#端使用此代码来获取数据:
//C# Code
[DllImport(UnmanagedDLLAddress)]
public static extern void GetData(ref IntPtr pData);
//and use it like
IntPtr pointer = IntPtr.Zero;
GetData(ref pointer);
byte[] data = new byte[3] // <===== think we know size
Marshal.Copy(pointer,data ,0,3);
Run Code Online (Sandbox Code Playgroud)
但总是"指针"为零所以Marshal.Copy抛出null异常我错了吗?TY
First, your C++ code puts the array to the stack. You need to allocate it some other way, for documentation start from here: http://msdn.microsoft.com/en-us/library/aa366533%28VS.85%29.aspx
Second, pData is a "normal" value argument, effectively a local variable. You assign to it, then it gets forgotten when function returns. You need it to be reference to pointer or pointer to pointer if you want it to be "out parameter" returning a value back. If you want to actually copy the array contents to the buffer pointed to by pData, then you need to use memcpy function from #include <cstring>.