I have to use a C library in C#. Here is the part that causes me trouble. The C function with the struct definition :
extern "C"__declspec(dllexport)unsigned short _stdcall read(unsigned short orderid, struct read_rb * request_ptr);
struct read_rb
{
// in
unsigned long C_Ref;
unsigned char Slot_Number;
unsigned char Index;
// out
unsigned char Length_s;
unsigned char * Data_s;
struct error _error;
};
So the unsigned char * Data_s is a pointer to an array that will contain output data. My C# code is below :
[DllImport("dpc2lib.dll")]
private static extern ushort read(ushort orderid, [In, Out] read_rb request_ptr);
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct read_rb
{
// in
public uint C_Ref;
public byte Slot_Number;
public byte Index;
// out
public byte Length_s;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
public byte[] Data_s;
public error _error;
}
I call it in my program like this
public float readData(byte slot_Number, byte index, byte data_Length)
{
read_rb Read_rb = new read_rb();
byte[] _dataReceived = new byte[5];
Read_rb.Data_s = _dataReceived;
int result = read(0, Read_rb);
}
It simply doesn't work. When read() function is called a AccessViolationEsception is thrown. The message is : Attempt to read or write Protected Memory. This is often an indicating that other memory is corrupt.
I tried various things but I really don't know how to handle this... Thanks for the help !