I have an application that is written in C# and uses a DLL written in C.
Through some delegate (function pointer), I have managed to invoke a C function. This function is expected to do a lot of processing on some data and then return the processed binary data back to C# code along with size of data.
The prototype for managed c# function is:
private unsafe delegate void MyCallback (IntPtr cs_buf, Int32 cs_size);
And I am calling this from my C code as:
void* c_buf = NULL;
int c_size = 0;
.... some processing here to fill buf and size......
MyCallback (c_buf, c_size);
In the managed C# code, I need to call a function from MyCallback that has the prototype:
void foo (byte[] cs_buf, int cs_size)
Now there is no problem with the cs_size value, but what is the correct way to use/pass the binary buffer from C code to C# code so that it can be used as a byte[] in C# code.
If what I am doing is the correct way, what should be the recommended way of converting the received IntPtr cs_buf to byte[]?
Thanks,
Vikram
You should use
Marshal.CopyAssuming that
cs_sizeis the size in bytes :By the way int this case
foo()don’t need to take acs_sizeparameter as it could use the.Lengthproperty of the array instead.Also with this, as the C# code copy the array, you could
free()the buffer from the C code just after calling the callback.Otherwise you will need either to export a
mylib_free()method from C or use a known memory allocator (NOTmalloc) likeLocalAlloc(From C) andMarshal.FreeHGlobal(From C#) under Windows.