go - 有什么方法可以在 Go 中动态解析 C 结构吗?

标签 go struct

我在 C 中定义了一个结构,例如:

struct SomeStruct
{
    int var1;
    bool var2;
    double var3;
    int var4[10];
    int var5[10][10];
}
struct SomeStruct entity;

某处有一个输入框,一些用户在 GO 中输入:

func("entity.var3")

它将返回 C 结构中 entity.var3 的值。

实际上我已经可以通过 cffi 在 python 中实现它并且:

def get_one_variable(buffer, setup):
    value = buffer
    for level in setup:
        if isinstance(level, str):
            value = getattr(value, level)
        else:
            [base, extends] = level
            value = getattr(value, base)
            for extend in extends:
                value = value[extend]
    return value

其中缓冲区是用“FFI.cdef”定义的 python cffi 数据指针,设置解析为:

def parse_variable(self, line):
    line = line.replace('\n', '').replace(' ', '')
    split = line.split('.')
    variable = []
    for child in split:
        match = self.BASE_EXT_REGEX.match(child)
        if match is None:
            variable.append(child)
        else:
            base_name = match.group('base_name')
            ext_name = match.group('ext_name')
            variable.append([base_name, [int(index) for index in
                                         ext_name.replace('[', ']').replace(']]', ']').strip(']').split(']')]])
    return variable

所以我可以动态解析“entity.var1”、“entity.var2”、“entity.var3”、“entity.var4[0]”、“entity.var5[0][1]”。

GO 中有类似的东西吗?

最佳答案

这是由 CGO 处理的,它是 Go 中的一个特殊包,可以轻松地与 C 语言集成。您可以阅读更多相关信息 herehere .根据您的示例,一个简单的 CGO 示例将是:

/*
struct SomeStruct
{
    int var1;
    bool var2;
    double var3;
    int var4[10];
    int var5[10][10];
}
*/
import "C"
import "fmt"

func main(){
    thing := C.struct_SomeStruct{}
    thing.var1 = C.int(5)
    fmt.Printf("My Struct's var field %d\n",int(thing.var1))
}

关于go - 有什么方法可以在 Go 中动态解析 C 结构吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49361806/

相关文章:

regex - 转到正则表达式以匹配带有括号的标签

pointers - Golang转换自定义类型并将其指针分配给可行的

go - 如何使用 TinyGo 解码 JWT token

go - 使用可变参数调用 golang println

go - 如果它具有相同的 'signature' 为什么不能使用来自不同包的类型? golang

ruby 在哪里定义结构

c++ - 从二进制文件读取会导致访问冲突

c - fread() 和 fwrite 在 C 编程中的工作原理

C: 结构指针数组

c++ - 在结构 vector 的结构 vector 的映射中存储数据