将C结构从主golang代码传递到其他golang包中的函数

问题描述 投票:0回答:1

我正在尝试将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 cgo
1个回答
0
投票

根据文档https://golang.org/cmd/cgo/

“ Cgo将C类型转换为等效的未导出的Go类型。由于未转换翻译,因此Go程序包不应在其导出的API中公开C类型:一个Go程序包中使用的C类型与另一个Go程序包中使用的C类型不同。“

有关此问题的github问题可在此处找到:https://github.com/golang/go/issues/13467

目前,建议不要在导出的API中公开C类型

© www.soinside.com 2019 - 2024. All rights reserved.