c++ - 初始化 union 内的结构 (C++)

标签 c++ x86

我正在用 C++ (Visual Studio 2010) 创建一个非常有限的、特定于域的 x86 汇编器,它动态生成指令、将其写入内存并执行,所有这些都在运行时进行。首先,我将它们写入一个临时字节流,然后将整个流写入一个 memcpy 中的可执行内存。

我使用以下代码构建一个movsd [imm32], xmm1 指令:

typedef unsigned char byte;
enum SSE2Register;

void WriteValueToMemory(double* dest, SSE2Register source)
{
    union
    {
        struct
        {
            byte insts[4];
            double* dest;
        };

        byte bytes[8];
    } movsd = 
    {
        // movsd [imm32], xmm1
        0xF2, 0x0F, 0x11, // Opcode
        0x05 + (8 * source), // ModR/M 
        dest // imm32
    };

    _stream.Write(movsd.bytes, sizeof(movsd.bytes));
}

此代码有效:三个操作码字节和 ModR/M 字节写入 insts,目标 (imm32) 写入 destbytes 包含原始字节中的整个指令,准备写入指令流。

但是,我很好奇这种初始化 union 的方法是否安全/可移植。 insts 的四个值和 dest 的值在一组大括号内初始化是否可以?

换句话说,这是执行此操作的正确、可移植方法,还是我应该采用不同的方法?

谢谢!

最佳答案

http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx

Anonymous Structures

A Microsoft C extension allows you to declare a structure variable within another structure without giving it a name. These nested structures are called anonymous structures. C++ does not allow anonymous structures.

You can access the members of an anonymous structure as if they were members in the containing structure.

但是,对于您正在做的事情,您不需要union

void WriteValueToMemory(double* dest, SSE2Register source)
{
    struct
    {
        byte insts[4];
        double* dest;
    } movsd = 
    {  // movsd [imm32], xmm1
        0xF2, 0x0F, 0x11, // Opcode
        0x05 + (8 * source), // ModR/M 
        dest // imm32
    };

    _stream.Write(&movsd, sizeof(movsd));
}

关于c++ - 初始化 union 内的结构 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7853643/

相关文章:

assembly - 为什么 BIOS 入口点以 WBINVD 指令开头?

assembly - 为什么汇编中字符串变量末尾包含 0?

c++ - 如何在 Lua 中处理 C++ 类构造函数失败

c++ - 使用 map 无法找到可能的运行时错误

c++ - gcc5.1 的新 libstdc++ 可能会分配大堆内存

linux-kernel - 如何将设备树 blob 添加到 Linux x86 内核启动?

C++ CodeBlocks 反汇编;代码太多了?

c++ - constexpr end istream (sentinel) 迭代器有什么意义?

c++ - g++ 不会在模板代码中发出 -Wsign-compare

linux - 在 Linux 中编译/运行汇编程序?