none
Marshalling Dynamic Sized Array from unmanaged code?? RRS feed

  • Question

  • Hi,

    I have a structure in C like:

    struct myStruct  
    {  
       int len;  
       byte[1] buf;  


    the buf is dynamically sized at runtime and I need to read this in c#.

    how can I copy this into c# and be able to read the whole length of the buffer??


    thanks,


    ed

    Tuesday, September 23, 2008 3:50 PM

Answers

  • Don't think there is away to get this marshalling correctly on its own. You can always write some logic to do it your self though.

    something like this will probably do the trick.
        struct myStruct     
        {     
            int len;     
            byte [] buf;     
     
            static myStruct FromIntPtr(IntPtr ptr)  
            {  
                myStruct res = new myStruct();  
                res.len = Marshal.ReadInt32(ptr);  
                res.buf = new byte[res.len];  
                IntPtr startByte = (IntPtr) ((int)ptr+4);  
                Marshal.Copy(startByte, res.buf, 0, res.len);  
                return res;  
            }  
        }   

    • Marked as answer by Ed-Elliott Wednesday, September 24, 2008 8:36 AM
    Tuesday, September 23, 2008 5:30 PM

All replies

  • Don't think there is away to get this marshalling correctly on its own. You can always write some logic to do it your self though.

    something like this will probably do the trick.
        struct myStruct     
        {     
            int len;     
            byte [] buf;     
     
            static myStruct FromIntPtr(IntPtr ptr)  
            {  
                myStruct res = new myStruct();  
                res.len = Marshal.ReadInt32(ptr);  
                res.buf = new byte[res.len];  
                IntPtr startByte = (IntPtr) ((int)ptr+4);  
                Marshal.Copy(startByte, res.buf, 0, res.len);  
                return res;  
            }  
        }   

    • Marked as answer by Ed-Elliott Wednesday, September 24, 2008 8:36 AM
    Tuesday, September 23, 2008 5:30 PM
  • Hi Ray  - I'll write some custom marshalling code!

    thanks,


    ed
    Wednesday, September 24, 2008 8:36 AM
  • Make sure your code still works 5 years from now:

      IntPtr startByte = (IntPtr) ((long)ptr + IntPtr.Size);

    Hans Passant.
    Wednesday, September 24, 2008 9:51 AM
    Moderator
  • nobugz said:

    Make sure your code still works 5 years from now:

      IntPtr startByte = (IntPtr) ((long)ptr + IntPtr.Size);


    Hans Passant.



    While I agree on the cast to long definitly don't add the size of a pointer. sizeof(int) stays 4 bytes even on 64 bit platforms, its the size of a long and pointers that change size when you move to 64 bit.

    Wednesday, September 24, 2008 12:27 PM
  • Oooops, you're right, it's an int.
    Hans Passant.
    Wednesday, September 24, 2008 12:37 PM
    Moderator