等效于C#中的结构

问题描述 投票:1回答:2

什么是C#等效于C中的以下结构:

struct  netbuf{
unsigned int    maxlen;
unsigned int    len;
char            *buf;
};

我将其翻译为:

public struct netbuf
{
    public uint maxlen;
    public uint len;
    public string buf;
};

但似乎不正确。

我有旧版C代码:

datagramm.addr.maxlen   = 0;
datagramm.addr.len      = 0;
datagramm.addr.buf      = (char*) 0;
datagramm.opt.maxlen    = 0;
datagramm.opt.len       = 0;
datagramm.opt.buf       = (char*) 0;

datagramm.udata.len   = sizeof(xliconf);
datagramm.udata.buf   = (char*)&xliconf;

xliconf.ccb_h.source = (uint8)ctrl_ed;
rval = xli_sndudata(ctrl_ed,&datagramm);

头中xli_sndudata的声明:

int xli_sndudata( int , struct t_unitdata *);

struct t_unitdata{
    struct netbuf   addr;     
    struct netbuf   opt;  
    struct netbuf   udata;   
};

Struct netbuf在上面。我需要在C#中翻译该代码。

c# pinvoke
2个回答
2
投票
[StructLayout(LayoutKind.Sequential, Pack = 0)]
public struct netbuf
{
    public ushort maxlen;
    public ushort len;
    public IntPtr buf;
};

0
投票

很好。尽管struct不是类,但语法非常接近,但有一些限制,如下所述:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/struct

结构还可以包含构造函数,常量,字段,方法,属性,索引器,运算符,事件和嵌套类型,尽管如果需要多个此类成员,则应考虑将您的类型设为类。

结构可以实现一个接口,但是它们不能从另一个结构继承。因此,无法将struct成员声明为受保护。

官方示例与您所拥有的非常相似。

© www.soinside.com 2019 - 2024. All rights reserved.