我试图将C结构从主要的golang代码传递到其他程序包,并收到类型转换错误。
程式码片段
C头文件test.h
#include<stdio.h>
struct err_struct {
int errnum;
};
Golang套件测试
package test
//#include<test.h>
import "C"
func ConvertCtoGoError(err_struct *C.struct_err_struct) {
//some code
}
golang主要代码
package main
import (
"./lib"
"fmt"
)
/*
#include"lib/test.h"
struct err_struct initialize_structure()
{
struct err_struct err;
err.errnum = 102;
return err;
}
*/
import "C"
func main() {
go_struct:= C.initialize_structure()
new_struct:= test.ConvertCtoGoError(&go_struct)
}
编译主要代码时,出现以下错误:
无法将&go_struct(* _Ctype_struct_err_struct类型)转换为* test._Ctype_struct_err_struct类型
当我尝试强制转换变量时,出现以下错误:
无法引用未导出的名称test。_Ctype_struct_dd_err_struct
无法将&go_struct(* _Ctype_struct_err_struct类型)转换为* test._Ctype_struct_err_struct类型
请帮我解决这个问题
最佳答案
根据go docs https://golang.org/cmd/cgo/,
"Cgo translates C types into equivalent unexported Go types. Because the translations are unexported, a Go package should not expose C types in its exported API: a C type used in one Go package is different from the same C type used in another."
可以在这里找到有关此问题的github问题:
https://github.com/golang/go/issues/13467
到目前为止,建议不要在导出的API中公开C类型
关于go - 将C结构从主要golang代码传递到不同的golang程序包中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59464147/