我正在使用用 c 语言编写的 dll。我已经将我需要的所有功能导入到我的 C# 程序中。大多数功能我都能正常工作,但有一些功能有问题。我遇到问题的函数需要一个结构作为输入。我假设我需要在 C# 中定义这个结构,我已经完成了,但我开始混淆自己,所以我将放弃我尝试过的东西。该结构相当长,所以我将简单介绍它在 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;
在 C# 中定义这些结构的正确方法是什么?谢谢
最佳答案
创建一个 C# 结构,对其应用 [StructLayout],并按照与 C 中相同的顺序列出字段。对于 FLAGS_TYPE 结构,您必须在字段上使用 [FieldOffset] 属性。 union 的所有成员都从相同的内存地址开始,因此对它们应用相同的 [FieldOffset(0)]。
更新:既然已经格式化,我认为您根本不需要使用 union 。使用单个 32 位整数,并通过按位运算获取不同的字段,这样更安全。
关于c# - 将 C 结构从 dll 转换为 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4548651/