Question

i have a c++ dll ,that has some extern function. and its look like this

//C++ Code
void GetData(byte * pData)
{
  byte a[] = {3,2,1};
  pData = a;
}

and i have use this code in C# side to get data :

//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);

but always "pointer" is zero so Marshal.Copy throw null exception where i did mistake ? ty

Was it helpful?

Solution

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>.

OTHER TIPS

Actually, like hyde told, use pData as "out" parameter. Because it's obviously a reference type and no value type, the called method shall take care about memory allocation. I used "ref" only for value types, like integer - e.g. getting the length of the array from the unmanaged method.

This way works fine for me, furthermore, i use the "cdecl" calling convention.

IntPtr aNewIntArray;
uint aNewIntArrayCount = 0;

NativeMethods.getEntityFieldIntArray(out aNewIntArray, ref aNewIntArrayCount);

int[] aNewIntArrayResult = new int[aNewIntArrayCount];
Marshal.Copy(aNewIntArray, aNewIntArrayResult, 0, (int)aNewIntArrayCount);

method declaration:

[DllImport(SettingsManager.PathToDLL, EntryPoint = "getEntityFieldIntArray", CallingConvention = CallingConvention.Cdecl)]
public static extern ErrorCode getEntityFieldIntArray(out IntPtr aNewIntArray, ref UInt32 aNewIntArrayCount);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top