views:

80

answers:

1

I'm trying to call the following C++ function that's wrapped up into a DLL:

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

My import statement looks like the following:

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

And my call routine looks like the following:

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:

A first chance exception of type 'System.AccessViolationException' occurred in xxx.dll Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

I'm just wondering if the fault lies in the way I'm marshaling my data or in my imported DLL file... anyone have any ideas?

A: 

This is likely occurring because the calling convention of the method is not as the marshaller is guessing it to be. You can specify the convention in the DllImport attribute.

You don't need the 'unsafe' keyword in the C# declaration here as it's not 'unsafe' code. Perhaps you were trying it with a 'fixed' pointer at one point and forgot to remove the unsafe keyword before posting?

Tergiver