How can you marshal an array of bytes in C #?

I am trying to call the following C ++ function, which is wrapped in a DLL:

unsigned char * rectifyImage(unsigned char *pimg, int rows, int cols) 

The import statement is as follows:

 [DllImport("mex_rectify_image.dll")] unsafe public static extern IntPtr rectifyImage( byte[] data, int rows, int columns); 

And my calling procedure is as follows:

 byte[] imageData = new byte[img.Height * img.Width * 3]; // ... populate imageData IntPtr rectifiedImagePtr = rectifyImage(imageData, img.Height, img.Width); Byte[] rectifiedImage = new Byte[img.Width * img.Height * 3]; Marshal.Copy(rectifiedImagePtr, rectifiedImage, 0, 3 * img.Width * img.Height); 

However, I keep getting a runtime error:

The first random exception of type System.AccessViolationException occurred in xxx.dll An attempt to read or write protected memory. This often indicates that another memory is corrupted.

I'm just wondering if the error is to blame for how I march my data or in an imported DLL file ... does anyone have any ideas?

+6
c # marshalling byte
source share
3 answers

This is most likely because the method calling convention is not the same as the marshaller guesses. You can specify the convention in the DllImport attribute.

You do not need to use the "unsafe" keyword in a C # declaration, as this is not "unsafe" code. Perhaps you tried using the "fixed" pointer at some point and forgot to remove the unsafe keyword before publishing?

+2
source share

not sure if this is your problem, but overall C ++ pointers map to IntPtr. so try changing your import statement:

 [DllImport("mex_rectify_image.dll")] unsafe public static extern IntPtr rectifyImage( IntPtr pData, int rows, int columns); 
+1
source share

rectifyImage Searches for a ponter for the 1st byte in the data block that you send to the block. Try imageData [0]

0
source share

All Articles