如何将 c 结构从 dll 转换为 C# [英] How do I convert c struct from dll to C#
问题描述
我正在将应用程序从 C++ 转换为 C#,并且对处理导入结构的正确方法有疑问.我正在尝试将结构从 c dll 转换为 c# c 中的结构看起来像这样
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;
当我使用 [StructLayout(LayoutKind.Sequentaial)] 时,数组的大小在 C# 中为 20 个字节.但是,如果看看我的工作 C++ 代码,它是 24 个字节.我把我的 c# 改成这样:
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.
谢谢
推荐答案
usinged long ul;
这是一个错字,但这绝对不是一个 ushort,而是一个 uint.
It's a typo, but that definitely isn't a ushort, it's an uint.
也不要使用FieldOffset,让编译器自己解决.现在 Marshal.SizeOf() 将返回 24,插入适当数量的填充.b
成员应该是 IntPtr btw.
Don't use FieldOffset either, let the compiler figure it out. Now Marshal.SizeOf() will return 24, the proper amount of padding is inserted. The b
member should be IntPtr btw.
这篇关于如何将 c 结构从 dll 转换为 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!