how to write correct PInvoke structs in C#?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • R Rajesh

    how to write correct PInvoke structs in C#?

    I have c++ structure and function as follows

    Code:
    struct InnerStruct
    {
      DWORD* data;
      INT16* values 
    };
    
    struct OuterStruct
    {
      char* name;
      InnerStruct* inner;
    }
    
    __declspec( dllexport) void Method(OuterStruct* value);
    I have created necessary PInvoke in C# as follows

    Code:
    [StructLayout(LayoutKind.Sequential)]
    public struct InnerStruct
    {
    public uint[] data;//Uint32*
    
    public Int16[] values;//Int16*
    }
    
    [StructLayout(LayoutKind.Sequential)]
    public struct OuterStruct
    {
    public string name;
    public InnerStruct[] inner;
    }
    
    [DllImport("dllname.dll", CallingConvention=CallingConvention.Cdecl)]
    public static extern void Method(ref OuterStruct value);
    When I pass OuterStruct parameter to unmanaged function, InnerRects data and values are giving wrong values in unmanaged side(looks like data corrupted). When, I used MarshalAs attribute over data and values with LPArray to make it c-style array it causing
    AccessViolation Execption stating "Attempted to read or write protected memory. This is often an indication that other memory is corrupt". Is any-one have idea on how to write correct PInvoke structs in C# for this, please help me.
    Last edited by Curtis Rutland; Nov 1 '10, 02:35 PM.
Working...