(gcc)中的封装结构去 [英] Packed Structs in (gcc)go

查看:130
本文介绍了(gcc)中的封装结构去的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些旧的C代码,使得有点使用压缩结构。我正在研究使用Go作为这个代码的包装,但是很难找到一种方法来传递或者为这些结构写定义。



示例: p>

  importunsafe; 

类型AlignTest结构{
c字节;
y int16;
z int16;
q int32;
}

func main(){

vr:= new(AlignTest);

fmt.Println(unsafe.Sizeof(* vr),\\\
);




$ b

返回12而不是1 + 2 + 2 + 4 = 9,我想要一个压缩/未对齐的结构。



我知道我可以创建一个字节数组并手动执行解析,但这看起来非常脆弱并且容易出错......

解决方案

您可能需要重新考虑您的架构 - 尝试将二进制输入传递到C层并使用现有的结构(您不会破坏您的架构,改变)。我假设结构包装看起来像这样:

  #ifdef WINDOWS 
#pragma pack(push)
#endif
#pragma pack(BYTEALIGNMENT)//例如#pragma pack(1)或#pragma pack(8)

// ---一些打包结构

#ifdef WINDOWS
#pragma (pop)
#endif
#ifdef POSIX
#pragma pack()
#endif

所有底层或第三方库都在做一些void *或const char *并对它们进行类型转换。因此,如果可能的话,尝试将数据转发到C层(您可以获取指针),并且根本不公开结构。


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...

解决方案

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:

#ifdef WINDOWS
#pragma pack(push)
#endif
#pragma pack(BYTEALIGNMENT) // e.g. "#pragma pack(1)" or "#pragma pack(8)"

//--- Some packed structs

#ifdef WINDOWS
#pragma pack(pop)
#endif
#ifdef POSIX
#pragma pack()
#endif

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.

这篇关于(gcc)中的封装结构去的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆