c# - C++ 到 C# worker 类(Class)的 union

标签 c# c++ unions

我只了解一点C++中的 union 是如何工作的。 我想我已经在 c# 类 mac_const 中复制了第一个注释 block 。 (如果不是请解释原因) 我现在并不担心效率,只是担心它能正常工作。 第二个评论区我什至不知道从哪里开始翻译它。 我不知道数据[2]映射到哪里,有人可以

//union {
//    unsigned short wd[4];
//    double data;
//    __int64 data64;
//}
//dbl_cnvt;

public class mac_const
{
    byte[] basedata = new byte[8];
    //public ushort[] wd
    public ushort this[byte index]
    {
        get { return BitConverter.ToUInt16(basedata, index * 2); }
        set { Array.Copy(BitConverter.GetBytes(value), 0, basedata, index * 2, 2); }
    }
    public double data
    {
        get { return BitConverter.ToDouble(basedata, 0); }
        set { basedata = BitConverter.GetBytes(value); }
    }
    public long data64
    {
        get { return BitConverter.ToInt64(basedata, 0); }
        set { basedata = BitConverter.GetBytes(value); }
    }
}


//union {
//    unsigned short cmd[4];
//    unsigned long data[2];
//    __int64 data64;
//}
//data_conversion;

public class data_conversion_csharp
{
    byte[] basedata = new byte[8];
    // the c++ class only 
    //public ushort[] cmd
    public ushort this[byte index]
    {
        get { return BitConverter.ToUInt16(basedata, index * 2); }
        set { Array.Copy(BitConverter.GetBytes(value), 0, basedata, index * 2, 2); }
    }
    public long[] data
    {
        // not sure what the mapping would be here, or if this should be data1 and data2 instead of an array
        ???
    }
    public long data64
    {
        ???
    }
}

编辑 - 关于 union 必要性的解释 @ffhighwind 我正在尝试移植一些使用 union 的 C++ 代码,因为它们应该是这样的 我不明白如何映射到数据中的第二个长整型数据

lng_cnvt.data64 = (dbl_cnvt.data64 >> 6) + (long)0x400000000000; 

if (data < 0)
{
    lng_cnvt.data64 = -lng_cnvt.data64;
    lng_cnvt.cmd[3] = 0;
    if (lng_cnvt.data64 == (__int64)0xC00000000000)
    {
        lng_cnvt.data64 = (__int64)0x800000000000; 
        exp -= 1;
    }
}
lng_cnvt.cmd[0] = (Ushort)((lng_cnvt.cmd[0] & 0xF000) | exp);
*ldata++ = lng_cnvt.ldata[0] & 0xFFFFFFL;
*ldata++ = ((lng_cnvt.data[0] >> 24) & 0x000FFL) |                                          
    ((lng_cnvt.data[1] << 8) & 0x0FFFF00L);

最佳答案

我没有投反对票,但如果没有超过 50 名代表,我就无法发表评论,所以也许其他人也有同样的情况。这样做的目的是什么?为什么不能直接转换为对象?

也许您想限制对象可以包含的类型。如果是的话,这可以吗?

class MyUnion
{
   object obj;

   MyUnion(SomeType o) { obj = o; }
   //... constructors for all accepted Types

   public object Value { get { return obj; } }
}

C# 是托管的,因此您不能真正期望对数据进行微调的低级控制。如果您想要像 C++ 那样的微调控制,您将需要 sizeofunmanaged unsafe code .

编辑:显然你可以使用乔纳森·蔡斯所说的属性进行 union 。

关于c# - C++ 到 C# worker 类(Class)的 union ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50958521/

相关文章:

c++ - 如何判断在哪个.SO库中赋予了C函数?

c - C 中的 typedef union 和 eclipse 自动完成

c++ - 共同的初始序列和比对

c++ - 联盟成员具有用户定义的构造函数

c# - (C#) 如何通过拖动和 "Open with ..."在我的程序中打开文件

c# - 如何访问 Windows 中的特殊目录?

C++函数式编程代码片段

c++ - 如何在 std::stringstream 的后代中调用 "this"上的 operator<<?

c# - 光标在 Visual Studio 2015 中消失

c# - C#中如何给字符串变量赋值