How do I convert c struct from dll to C#

Posted by poco on Stack Overflow See other posts from Stack Overflow or by poco
Published on 2011-01-03T19:52:56Z Indexed on 2011/01/03 19:53 UTC
Read the original article Hit count: 142

Filed under:
|
|
|

I am converting a application from c++ to C# and have a question about the proper way to handle importing structs. I am attempting to convert a struct from a c dll into c# The struct in c looks like this

typedef struct card_info
{
  ushort r;
  ushort s;
  enum_a a;
  usinged long ul;
  ushort n;
  ushort* b;
  ushort id;
} CARD_INFO;

when i use [StructLayout(LayoutKind.Sequentaial)] the size of the array is 20 bytes in c#. However, if take a look at my working c++ code it is 24 bytes. I changed my c# to look like this:

[StructLayout(LayoutKind.Explicit)]
public struct CardInfo
{
  [FieldOffset(0) public ushort r;
  [FieldOffset(2) public ushort s;
  [FieldOffset(4) public EnumA a;
  [FieldOffset(8) public ushort ul;
  [FieldOffset(12) public ushort n;
  [FieldOffset(16) public UInt32 b;
  [FieldOffset(20) public ushort id;
}

This seems to compile but I'm not convinced this is the correct way to go about doing this. Please let me know if this is correct or if there is a better way.

Thanks

© Stack Overflow or respective owner

Related posts about c#

Related posts about dll