简体   繁体   English

将C ++结构转换为C#结构

[英]Converting c++ struct to c# struct

Can anybody tell me how do I convert the following struct to c# 谁能告诉我如何将以下结构转换为C#

typedef struct DES_ks
{
    union
    {
        DES_cblock cblock;
        /* make sure things are correct size on machines with
         * 8 byte longs */
        DES_LONG deslong[2];
    } ks[16];
} DES_key_schedule

You will need to look up the typedef's for DES_cblock and DES_LONG to translate this. 您将需要查找DES_cblock和DES_LONG的typedef来进行翻译。 However, to get you started, you'll want to read up on StructLayoutAttribute . 但是,为了入门,您需要阅读StructLayoutAttribute The way to translate C unions into C# is to use an explicit layout structure: 将C联合转换为C#的方法是使用显式的布局结构:

[StructLayout(LayoutKind.Explicit)]
public struct DES_ks
{
  [FieldOffset(0)]
  public DES_cblock cblock;
  [FieldOffset(0)]
  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
  public DES_LONG[] deslong;
}

Thanks to @Konrad for fixing my temporary insanity; 感谢@Konrad解决我的暂时精神错乱; because you want to produce a union, you need all of the fields to overlap in memory. 因为您要产生一个并集,所以需要所有字段在内存中重叠。 This is achieved in C# by telling the compiler to lay them out at the same offset, in this case 0. 在C#中,这是通过告诉编译器以相同的偏移量(在本例中为0)进行布局来实现的。

C# does not have unions. C#没有联合。 . The closest you can come is using FieldOffset. 最接近的是使用FieldOffset。 However, if your struct isn't being passed directly to external functions, you're likely better off using a more OO approach. 但是,如果未将结构直接传递给外部函数,则最好使用更多面向对象的方法。 I'd suggest just creating a struct with arrays of both types and set the one you aren't using to null. 我建议只用两种类型的数组创建一个结构,然后将不使用的结构设置为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM