go - 将C结构从主要golang代码传递到不同的golang程序包中

标签 go cgo

我试图将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/

相关文章:

c - 从 []byte 到 char*

linux - 在 darwin for linux 上交叉编译 CGO 应用程序

go - 为什么CGO无法在C中直接调用函数指针?

types - 戈朗 : Export C fields to be externally visible using CGo

arrays - 如何在golang中将项目添加到struct中的数组

go - 从文件中读取字符串、整数和字节

go - 有没有办法在golang中计算类型的大小?

go - 从net/http包中的* urlError访问Timeout()方法

go - linter err113 : do not define dynamic errors,改用包装的静态错误

go - cgo 和 pkg 配置