Say, I’ve got that prototype of a function that is exposed on a DLL:
int CALLBACK worker (char* a_inBuf, int a_InLen,
char** a_pOutBuf, int* a_pOutLen,
char** a_pErrBuf, int* a_pErrLen)
I’m sure that it’s ridiculously easy to call that DLL function from my C# code but it doesn’t work with this code:
[DllImport("mydll.dll")]
public static extern int worker(
[In, MarshalAs(UnmanagedType.LPArray)] byte[] inBuf,
int inputLen,
[Out, MarshalAs(UnmanagedType.LPArray)] byte[] outBuf,
out int outputLen,
[Out, MarshalAs(UnmanagedType.LPArray)] byte[] errBuf,
out int errorLen);
...
int outputXmlLength = 0;
int errorXmlLength = 0;
byte[] outputXml = null;
byte[] errorXml = null;
worker(input, input.Length, output, out outputLength, error, out errorLength);
I get an access violation when I’m going to fetch the memory for output and error inside my unmanaged library (and therefore de-reference the passed pointer):
*a_ppBuffer = (char*) malloc(size*sizeof(char));
-
How do I write the
DLLIMPORTstatement in my C# code for this function? -
How do I actually call the function so that
a_pOutBufanda_pErrBufare accessible and notnullfrom withinworker(i.e. use a real double pointer)?
Your current definition will not work. The
workerfunction is allocating memory inside of the function and writing to that memory.The P/Invoke layer does not support marshaling C-style arrays that are allocated in this way, as it has no way of knowing just how large the array will be when the call returns (unlike say, a
SAFEARRAY).That’s also why returning pointers to arrays from API functions is generally a bad idea, and the Windows API is written in such a way that the memory allocation is handled by the caller.
That said, you want to change the P/Invoke declaration of
workerto this:In doing this, you’re indicating that you’re going to marshal the arrays manually (the
outBufanderrBufparameters are going to be set for you); you’re passing the reference to the pointer (double-indirection, that’s yourchar**) and then have to read from them using other indicators for bounds checking (in this case, theoutputLenanderrorLenparameters).You would marshal the data out of the pointers upon return like so:
That said, you have another problem. Because the memory was allocated inside the function, you have to free the memory. Since you’re using
mallocto allocate the memory, you need to pass the twoIntPtrinstances back to unmanaged code in order to havefreecalled on them.If you were allocating memory in unmanaged code using
LocalAllocorCoTaskMemAllocthen you could use theFreeHGlobalorFreeCoTaskMemmethods respectively on theMarshalclass to free the memory on the managed side.