none
Byte array size got changed after DllImport call to C++ dll and how to fix the byte array size at interop? RRS feed

  • Question

  • I need to convert the following C++ code to C#.

     

    Code Snippet

    extern "C" __declspec(dllexport)long ReadRq(BYTE address, BYTE numBytes, BYTE* pData);
    extern "C" __declspec(dllexport)long Write(BYTE address, BYTE numBytes, BYTE* pData);

     

    {

     BYTE dataBuffer[2048];

    ...

     dataBuffer[0] = 0x05;
     result = Write(0x6B, 1,&dataBuffer[0]);
     result = ReadRq(0x6B, 4, &dataBuffer[0]);

    ...

    }

     

     

    This is what I converted to C#,

     

    Code Snippet

            [DllImport("foo.dll", SetLastError = true)]
            internal static extern int ReadRq(byte address, byte numBytes, ref byte[] pData);

            [DllImport("foo.dll", SetLastError = true)]
            internal static extern int Write(byte address, byte numBytes, ref byte[] pData);

     

    {

                byte[] dataBuffer = new byte[2048];

    ...

                dataBuffer[0] = 0x05;
                result = Write(0x6B, 1, ref dataBuffer);  // Write data from dataBuffer
                result = ReadRq(0x6B, 4, ref dataBuffer); // Read data to dataBuffer

    ...

    }

     

     

    The issue is -- with my C# code, after Write() finished, the array size of dataBuffer[] became 1.

     

    However, with C++, there is no change of the dataBuffer array size which is still 2048 intact.

     

    Since there was dataBuffer array size change in C# implementation, it throws 'System.IndexOutOfRangeException' exception when it looks for dataBufferNo value where n > 0.

     

    I'm sure I miss something on C# implementation, or I might need to marshal the size of the byte[] array at DllImport. But I'm not 100% sure what really is the root cause..

     

    Your help is greatly appreciated.

     

    Thanks.

     

    Wednesday, April 2, 2008 2:19 PM

Answers

  • Actually, byte[] itself is reference type and you pass it as ref, so the C++ side will modify the dataBufffer itself instead of the Array pointed by it on the managed heap. So you should remove the ref modifier before the byte[] argument and try again.
    Friday, April 4, 2008 2:10 AM