converting C to C#

2019-02-21 00:10发布

I'm trying to convert this C code to C#, is there a C# equivalent to the C union typedef?

struct sockaddr_in {
    short   sin_family;
    u_short sin_port;
    struct  in_addr sin_addr;
    char    sin_zero[8];
};

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;

Thanks.

标签: c# c struct unions
2条回答
时光不老,我们不散
2楼-- · 2019-02-21 00:42

You may check out the following page. This being said, in .NET you have classes that allows you to work directly with sockets and TCP/IP such as Socket, TcpListener, TcpClient and you don't need to translate C code blindly.

查看更多
狗以群分
3楼-- · 2019-02-21 00:58

Whilst the others definitely have a point - this is likely something you really don't need to do - there is a way to simulate unions in C# using StructLayoutAttribute (example of simulating a union here).

But don't do it. The purpose of this C union seems to be to permit bit twiddling parts of a 4 byte long. Using a union in this way depends on byte order knowledge of the target architecture, something that C# cannot guarantee.

In C# - or any other language where portability is a concern - if you want to get or set the high byte/low byte/etc you need to use explicit bit shifting as explained here.

But then don't do that either. Do like others have said and don't port this code. Someone's already done it for you, most likely Microsoft in the built in libraries ;).

查看更多
登录 后发表回答