D 可以在编译时将Foo强制转换为ubyte[size]吗?
是否可以在编译时将D 可以在编译时将Foo强制转换为ubyte[size]吗?,d,D,是否可以在编译时将Foo强制转换为ubyte[size] 这里有更多的上下文: 结构代数(类型…) if(Types.length8*i); } 其他的 { //处理浮动类型、数组等。 } 返回结果; } 结构 { int x,y; } 静态不可变字节=重新解释(S(42,42)); pragma(msg,字节); 这种方法有一个巨大的限制:您需要手动调整到适当的ABI。像endianess这样的东西是微不足道的,但是正确地处理字段对齐可能是一件痛苦的事情(在这段代码中我甚至没有尝试这样做)
Foo
强制转换为ubyte[size]
这里有更多的上下文:
结构代数(类型…)
if(Types.length分支转换为ubyte[maxSize]
。我不知道有任何“干净”的方法(一种可以利用ABI编译器知识的方法),因为CTFE在防止重新解释方面非常保守。但是,如果这是一个拦截器,则可以利用struct ABI非常简单的事实手动构建字节数组:
import std.traits;
ubyte[T.sizeof] reinterpret (T) ( T x )
if (!hasIndirections!T)
{
typeof(return) result;
static if (is(T == struct))
{
size_t offset = 0;
foreach (ref field; x.tupleof)
{
result[offset .. offset + field.sizeof] = reinterpret(field);
offset += field.sizeof;
}
}
else static if (is(T : ulong))
{
for (auto i = 0; i < x.sizeof; ++i)
result[i] = cast(ubyte) (x >> 8*i);
}
else
{
// handle floating types, arrays etc.
}
return result;
}
struct S
{
int x, y;
}
static immutable bytes = reinterpret(S(42, 42));
pragma(msg, bytes);
importstd.traits;
ubyte[T.sizeof]重新解释(T)(T x)
if(!hasIndirection!T)
{
返回结果的类型;
静态if(is(T==struct))
{
尺寸偏差=0;
foreach(参考字段;x.tupleof)
{
结果[偏移量..偏移量+字段.sizeof]=重新解释(字段);
偏移量+=field.sizeof;
}
}
如果(是(T:ulong))则为静态
{
用于(自动i=0;i>8*i);
}
其他的
{
//处理浮动类型、数组等。
}
返回结果;
}
结构
{
int x,y;
}
静态不可变字节=重新解释(S(42,42));
pragma(msg,字节);
这种方法有一个巨大的限制:您需要手动调整到适当的ABI。像endianess这样的东西是微不足道的,但是正确地处理字段对齐可能是一件痛苦的事情(在这段代码中我甚至没有尝试这样做)