问题描述
是否存在与C联合typedef等效的C#?
我应该如何将以下代码转换为c#..
任何人都可以用C#等效代码来帮助我.
Is there a C# equivalent to the C union typedef?
how should i convert the following code into c#..
Can any one Please Help me with the C# equivalent Code.
typedef struct in_addr {
union {
struct {
u_char s_b1,s_b2,s_b3,s_b4;
} S_un_b;
struct {
u_short s_w1,s_w2;
} S_un_w;
u_long S_addr;
} S_un;
} IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;
谢谢Advance.
Thank you in Advance.
推荐答案
using System.Runtime.InteropServices;
//...
[StructLayout(LayoutKind.Explicit)]
struct BytePart {
[FieldOffset(0)]
public byte B1;
[FieldOffset(1)]
public byte B2;
[FieldOffset(2)]
public byte B3;
[FieldOffset(3)]
public byte B4;
}
[StructLayout(LayoutKind.Explicit)]
struct ShortPart {
[FieldOffset(0)]
public ushort W1;
[FieldOffset(2)]
public ushort W2;
}
[StructLayout(LayoutKind.Explicit)]
struct InAddress {
[FieldOffset(0)]
public BytePart BytePart;
[FieldOffset(0)]
public ShortPart ShortPart;
[FieldOffset(0)]
ulong Address;
}
这是完全等效的定义,没有嵌套结构:
This is a fully equivalent definition without nested structures:
[StructLayout(LayoutKind.Explicit)]
struct InAddress {
//bytes:
[FieldOffset(0)]
public byte B1;
[FieldOffset(1)]
public byte B2;
[FieldOffset(2)]
public byte B3;
[FieldOffset(3)]
public byte B4;
//words:
[FieldOffset(0)]
public ushort W1;
[FieldOffset(2)]
public ushort W2;
//long address:
[FieldOffset(0)]
ulong Address;
}
参见:
http://msdn.microsoft.com/en-us/library/system. runtime.interopservices.structlayoutattribute.aspx [ ^ ],
http://msdn.microsoft.com/en-us/library/system. runtime.interopservices.fieldoffsetattribute.aspx [ ^ ].
See:
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx[^],
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.fieldoffsetattribute.aspx[^].
这篇关于将C转换为C#代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!