我在 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 语言集成。您可以阅读更多相关信息 here和 here .根据您的示例,一个简单的 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/