我正在尝试使用C#应用程序中的C DLL结构。我无法获得我正在处理的结构的等效数据类型。我正在处理来自C:
的这些数据类型struct teststruct {
unsigned short protocol_type; //c#'s UInt16 ?
unsigned char hardwareSize; //c#'s byte?
UCHAR dest[6]; //unsigned char and thus byte in c#?
unsigned char ip_version : 4; //How to get the exact same thing in c#?!!
unsigned char Nonce_Sum_Flag: 1; //the same as above
unsigned char ip[4]; // !!
unsigned short in6_addr_src[8]; // !!
char* astring; //string!?
char anarray[10]; //string? or char[]?
const char* conststring; //string? or array[] or char[]?
};
对于结构本身,我认为提前预定
[StructLayout(LayoutKind.Sequential)]
就足够了。
这是我的C#结构;很明显,我坚持使用中间的两种和最后3种数据类型。我不知道如何去做他们!
[StructLayout(LayoutKind.Sequential)]
public struct teststruct
{
public UInt16 protocol_type; //c's unsigned short ?
public byte hardwareSize; //c's unsigned char?
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public byte[] dest; //c's unsigned char ?
unsigned char ip_version : 4; //How to get the exact same thing in c#?!!
unsigned char Nonce_Sum_Flag : 1; //the same as above
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] ip; // right?!
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public UInt16[] in6_addr_src; // !!
char* astring; // !?
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public byte[] anarray; //string? or char[]?
const char* conststring; //string? or array[] or char[]?
}
有人会特别建议我关于比特分配的C独特概念吗?我的意思是这一行:
unsigned char Nonce_Sum_Flag: 1;
以及最后3个!
答案 0 :(得分:2)
将[MarshalAs(UnmanagedType.LPStr)]string
用于char*
对于位域unsigned char ip_version : 4;
,c#中没有直接支持,你自己实现这个link可能会有所帮助。
答案 1 :(得分:2)
大多数数据类型都被猜对了。
查看下表,它是一个C++
数据类型的表,它应该是C#
数据类型,也包括大小。
列顺序:C ++数据类型,C#数据类型,大小
BOOL bool 1 byte
BYTE byte 1 byte
CHAR byte 1 byte
DECIMAL Decimal 16 bytes
DOUBLE double 8 bytes
DWORD uint, UInt32 4 bytes
FLOAT float, single 4 bytes
INT, signed int int, Int32 4 bytes
INT16, signed short int short, Int16 2 bytes
INT32, signed int int, Int32 4 bytes
INT64 long, Int64 8 bytes
LONG int, Int32 4 bytes
LONG32, signed int int, Int32 4 bytes
LONG64 long, Int64 8 bytes
LONGLONG long, Int64 8 bytes
SHORT, signed short int short, Int16 2 bytes
UCHAR, unsigned char byte 1 byte
UINT, unsigned int uint, UInt32 4 bytes
UINT16 ushort, UInt16 2 bytes
UINT32, unsigned int uint, UInt32 4 bytes
UINT64 ulong, UInt64 8 bytes
ULONG, unsigned long uint, UInt32 4 bytes
ULONG32 uint, UInt32 4 bytes
ULONG64 ulong, UInt64 8 bytes
ULONGLONG ulong, UInt64 8 bytes
void*, pointers IntPtr x86=4 bytes, x64=8 bytes
<子> Source 子>
答案 2 :(得分:2)
在C#中,您必须将所有位字段作为单个字节或int读取,并使用位掩码函数对它们进行打包/解压缩。