I am using a dll that was written in c. I have imported all the functions i need into my c# program. Most of the functions i can get to work properly but am having trouble with a few. The functions i am having issues with require a struct as input. I assume i need to define this struct in C#, which i have done but I am starting to confuse myself so I will leave what i have attempted out. The struct is fairly long 开发者_如何学Pythonso i will simply what it looks like in c:
typedef struct chain_link_info
{
unsigned short command;
unsigned long* buff_id;
FLAGS_TYPES flags; // this is a union that i will list below
} CHAIN_LINK_INFO;
typedef union flags_type
{
unsigned long ulong;
struct
{
unsigned short std_flags;
unsigned short high
} ushort;
struct
{
unsigned int a : 1;
unsinged int b : 1;
unsinged int c : 1;
unsinged int d : 1;
unsinged int e : 2;
unsinged int f : 1;
unsinged int g : 1;
unsinged int h : 1;
unsinged int i : 1;
unsinged int j : 1;
unsinged int k : 1;
unsinged int l : 1;
unsinged int m : 1;
unsinged int n : 1;
unsinged int o : 1;
unsigned int high_word :16
} std_bits;
} FLAGS_TYPE;
what is the proper way to define these stucts in C#? Thank you
Create a C# struct, apply [StructLayout] to it, and list the fields in the same order as in C. For the FLAGS_TYPE structure, you have to use the [FieldOffset] attribute on the fields. All members of a union start at the same memory address, so apply the same [FieldOffset(0)] to them.
UPDATE: now that it's formatted, I think you don't need to use unions at all. Use a single 32 bit integer, and get the different fields with bitwise operations, it's safer that way.
The C declaration isn't valid, makes it hard to give a good answer. You cannot normally deal with bit fields but in this special case it works since they're all a multiple of 8 bits. You need [StructLayout(LayoutKind.Explicit)] and use [FieldOffset(x)] for each field. The badly named unsigned long, std_flags and a are at offset 0. b at 1. high and high_word at 2.
FieldOffset
is byte unit.
So, You can express upto byte only through FieldOffset
.
You may create your own FieldOffset
.
精彩评论