(gcc)go 中的打包结构
我有一些旧的 C 代码,它们在某种程度上大量使用了打包结构。我正在考虑使用 Go 作为此代码的包装器,但很难找到传递甚至编写这些结构的定义的方法。
示例:
import "unsafe";
type AlignTest struct {
c byte;
y int16;
z int16;
q int32;
}
func main() {
vr := new(AlignTest);
fmt.Println(unsafe.Sizeof(*vr), "\n");
}
返回 12,而不是我想要的打包/未对齐结构的 1+2+2+4 = 9。
我知道我可以创建一个字节数组并手动进行解析,但这似乎非常脆弱且容易出错......
I have some old C code that makes somewhat heavy use of packed structures. I'm looking into using Go as a wrapper for this code, but am having difficulty finding a way to pass or even write definitions for these structures.
Example:
import "unsafe";
type AlignTest struct {
c byte;
y int16;
z int16;
q int32;
}
func main() {
vr := new(AlignTest);
fmt.Println(unsafe.Sizeof(*vr), "\n");
}
Returns 12 rather than the 1+2+2+4 = 9 that I would want with a packed/unaligned struct.
I know that I could just create a byte array and do the parsing manually, but that seems very brittle and error prone...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以尝试这样的事情。
。
You could try something like this.
.
您可能想要重新考虑您的架构 - 尝试将二进制输入向下传递到 C 层并使用现有结构(您不会破坏不更改的内容)。我假设结构打包看起来像这样:
所有底层或第 3 方库所做的就是获取一些 void* 或 const char* 并将其类型转换为这些。因此,如果可能的话,尝试将该数据转发到 C 层(您可以在其中获取指针)并且根本不公开结构。
You may want to rethink your architecture- try passing the binary input down to the C layer and use the existing structures (you won't break what you don't change). I'm assuming the structure packing looks something like this:
All the underlying or 3rd Party libs are then doing is taking some void* or const char* and typecasting it to these. So if possible, try forwarding that data into a C layer (where you can get pointers) and don't expose the structures at all.
没有办法告诉 gccgo 编译打包结构。我能想到的最好的解决方案是手动添加填充:
There's no way to tell gccgo to compile packed structures. The best solution I can think of is to manually add padding:
这有效:
输出:
This works:
Output: