-
Notifications
You must be signed in to change notification settings - Fork 0
73 c 与c#的映射
Jinxin Chen edited this page Sep 15, 2017
·
2 revisions
在某些场景下,我们需要让c#的struct和c的struct保持一致,本文做简单的介绍。
假设现在c struct如下:
typedef struct tagDICTIONARY
{
unsigned int key;
unsigned int count;
WORD word[1000] = { 0 };
}DICTIONARY;
typedef struct tagWORD
{
WCHAR letters[10] = { 0 };
unsigned short key;
int enabled : 1;
int reversed : 7;
}WORD;
对应的c# struct如下:
[StructLayout(LayoutKind.Sequential)]
struct Dictionary
{
public uint Key;
public uint Count;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1000)]
public Word[] WordItem;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct Word
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public string Letters;
public ushort Key;
public uint Reserved;
}
如下这段标记声明了struct的内存对其方式,事实上这是默认值,可以不用写
[StructLayout(LayoutKind.Sequential)]
具体的可以参考:
http://blog.csdn.net/qq_18229381/article/details/52846708?locationNum=1&fps=1
结构体数组定义默认是不支持定义数组大小的,可以用下面的方式来定义一个长度为1000的数组
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1000)]
WCHAR letters[10]定义,到c#这边转换为:
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public string Letters;
enabled : 1, reversed : 7分别按位定义了两个数据,c#不支持这种定义,不过可以通过位运算来实现:
Word.Reversed += 1; // 设置enabled的值
Word.Reversed += 8 < 1; // 设置reversed的值