1

is it possible to pass a Byte[] from C# to unmanaged C++ and have it modified inside C++ reading its value back in C#? Something like:


C#:
[DllImport("MyDll.dll")]
public static extern bool UnmanagedFunction(ref Byte[] a, short b, ref ulong c);
...
bool success;
Byte[] a = new Byte[65];
ulong c = 0;
success = UnmanagedFunction(ref a, (short)a.Length, ref c);

C++:
extern "C" __declspec(dllexport) BOOL WINAPI UnmanagedFunction(
    __inout_ecount(b)       PBYTE          a, 
    __in                    INT16          b,
    __out                   DWORD          c
) {
    BOOL success = FALSE;
    PBYTE uA;
    OVERLAPPED d;
    ...
    success = ReadFile(
        readHandle,
        uA,
        b,
        &c,
        &d);
   if ( success ) {
       a = uA;
   }
   free(uA);
   return success;
}

When I try to read the variable "a" on C# after the invocation of "UnmanagedFunction" it shows only the first position of the array, I'm sorry about the C code I'm really new to pointers and references in C++

I have tried to iterate through "uA" "c" times setting each position on "a", each position is defined but when the code returns to its managed section I get an exception telling me the memory is corrupt, something like:

for ( int i = 0; i < c; ++i )
    a[i] = uA[i];

I have seen functions returning an IntPtr and then invoking the Marshal.Copy on the managed side, but I was wondering if would it be possible to something close to what I'm trying to achieve above

thanks in advance!

leandro koiti
  • 423
  • 1
  • 7
  • 18
  • 1
    A `ref byte[]` is a `byte**`, AFAIK – SLaks Mar 15 '13 at 19:54
  • Hey SLaks, thanks a lot, I've tried with byte** but when the function returns to its managed side I get the following exception: "Attempted to read or write protected memory. This is often an indication that other memory is corrupt." please correct me if I'm wrong but I'm thinking this exception is telling me that the array I passed can't be changed on its unmanaged side? when I changed to byte** I removed the "supporting" array (uA) and sent "a" directly to the functions – leandro koiti Mar 15 '13 at 20:15
  • @JimMischel I'm going to try that solution because I'm not sure if I've already tried it, but my problem is with returning the modified array back, and not simply passing it to C++ (which I can do when I don't have to modify it inside C++) – leandro koiti Mar 15 '13 at 20:19
  • @JimMischel that worked thanks a lot! although the solution marked didn't work for me, I used one of the comments from the same thread: `code`unsafe { IntPtr intPtr; ulong c = 0; fixed (byte* pByte = a) intPtr = new IntPtr((void *)pByte); success = UnmanagedFunction(intPtr, (short)a.Length, ref c);}`code` – leandro koiti Mar 15 '13 at 20:35

0 Answers0