我正在用 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
) 写入 dest
和 bytes
包含原始字节中的整个指令,准备写入指令流。
但是,我很好奇这种初始化 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/