I have a function in C++ and exported in DLL. the function is
LONG LOGIN(LPDEVINFO info);
the struct of LPDEVINFO is:
struct{
BYTE sSerialNumber[20];
} *LPDEVINFO;
to pass LPDEVINFO parameter, I have defined a class in managed code:
class DEVINFO{
Byte[] sSerialNumber = new Byte[20];
}
and then P/Invoke like this:
[DllImport ('MyDll.dll')]
public static extern Int32 LOGIN(DEVINFO info);
and then call it in C#:
DEVINFO info = new DEVINFO();
Int id = LOGIN(info)
When I run this code, I got following error:
An unhandled exception of type 'System.AccessViolationException' occurred in WindowsFormsApplication1.exe
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I think the problem is caused by the array sSerialNumber. But I do not know how to define it in a right way.
Thanks in advance!
LONGis defined as a 64-bit integer type in C++, you'll have to either map export the function asextern Int64 LOGIN(DEVINFO info);orextern long LOGIN(DEVINFO info);. As for yourDEVINFOclass, I would make it a struct and apply the attribute[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]to the byte array. see this answerLONGis 32 bit integer in C and C++ on Windows.LONGis the same asLONGand is 32 bits in C on Windows. In C#longis 64 bits.