c# - 将 C 结构从 dll 转换为 C#

标签 c# c dll import struct

我正在使用用 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/

相关文章:

c# - 设计模式 : child class calling base class

java - ODBC 与 JDBC 性能对比

c++ - MFC从DLL导入对话框

c++ - 访问某个dll方法时访问冲突读取位置

c# - 使用 C# 反序列化 XML HTTP 响应

c# - 在 ElasticSearch 5.5 中使用摄取插件时如何获取术语向量?

C# SSIS 脚本任务 - 格式化 Excel 列时添加千位分隔符

c - C中的定点数字振铃滤波器

c - 是否有一种有效且安全的方法来反转数组中的所有元素?

python - Windows 上的 ctypes : depending dlls not found