How to pass binary data from C++ dll to a C# application via Interop?  
Author Message
knave





PostPosted: Common Language Runtime, How to pass binary data from C++ dll to a C# application via Interop? Top

Hi,

I have a slight problem with passing binary data from a C++ dll to a C# application and I hope someone over here is able to give me some guidance.

Some background info:
I have a C++ dll that extracts a char* of binary data containing an image, e.g. JPG, GIF.

If the output is written from the C++ dll as shown below, it works. The jpeg file is output correctly.

FILE* pJPGFile = fopen("E:\\test.jpg","wb");
fwrite(myBinaryData,1,size_h,pJPGFile);
fclose(pJPGFile);

However, when I tried to "send" this block of data to a C# application, the byte array (the datatype I'm using on the C# end) doesn't have the complete data.

_declspec(dllexport) bool GetImageInfo( BYTE* imageData )
{
//..some processing
imageData = (BYTE*) myBinaryData;
}


.NET Development5  
 
 
Mattias Sjogren





PostPosted: Common Language Runtime, How to pass binary data from C++ dll to a C# application via Interop? Top

It doesn't work because the C++ code doesn't copy the image data, it just overwrites the pointer that your C# passes in. You need to do something like

memcpy(imageData, myBinaryData, MyIMAGESIZE);

instead. I would recommend passing in the buffer size as an additional parameter unless you know that it's constant.



 
 
knave





PostPosted: Common Language Runtime, How to pass binary data from C++ dll to a C# application via Interop? Top

Thanks for the help.

Yup that is precisely the answer. I tried both of my C# methods and it works after the memcpy call is added to the c++ code.

btw, the buffersize is obtained from another interop call accessing the same file, so the filesize is already provided.

Knave