douna3367 2018-03-19 11:24
浏览 95
已采纳

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

I defined a struct in C like:

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

And somewhere there was a input box that some user input in GO:

func("entity.var3")

It will return value of entity.var3 in C struct.

Actually I could already implement it in python by cffi and:

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

Where buffer is python cffi data pointer defined with "FFI.cdef" and setup resolved by:

def parse_variable(self, line):
    line = line.replace('
', '').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

So I can dynamically resolve "entity.var1", "entity.var2", "entity.var3", "entity.var4[0]", "entity.var5[0][1]".

Is there something or someway similar in GO?

  • 写回答

1条回答 默认 最新

  • doupingdiao3546 2018-03-19 12:35
    关注

    This is handled by CGO which is a special package in Go that allows for easy C integration. You can read more about it here and here. Given your examples, a simple CGO example would be:

    /*
    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
    ",int(thing.var1))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题