Go无法调用C ++函数

I have been using cgo to interface between Go and C. However, when trying to do the same for Go and C++, I get a compile error every time I attempt to call a function. Using go build . from the code's directory, I get the following errors:

./main.go: In function 'void _cgo_3612c872201c_Cfunc_getint(void*)':
./main.go:48:53: error: invalid conversion from 'void*' to '_cgo_3612c872201c_Cfunc_getint(void*)::<anonymous struct>*' [-fpermissive]
./main.go:54:4: error: invalid conversion from 'void*' to '_cgo_3612c872201c_Cfunc_getint(void*)::<anonymous struct>*' [-fpermissive]

I've put a super simple example below which shows the problem.

main.go:

package main

/*
#cgo CFLAGS: -x c++

int getint()
{
    return 1;
}
*/
import "C"

import (
    "fmt"
)

func main() {
    fmt.Println(C.getint())
}

Does anyone know if this is a bug in cgo, or something wrong with how I wrote the code? According to the cgo documentation, C++ is supported. I'm using Go version 1.7.5 for linux/amd64.

Thanks so much!

cgo

1个回答



我可能是错的,但是我认为 cgo </ code>仅在知道如何调用A的意义上支持C ++。 非Go文件上的C ++编译器看起来像包含C ++源代码,仅此而已。</ p>

问题是C ++编译器使用了所谓的”修改“ 表示从编译文件中导出的符号。 导出符号最初\只希望用于类似C的语言,其中所有可以导出的都是普通的
函数和变量,但是C ++添加了类和函数重载,
并从已编译(“对象”)文件中导出此类符号, C ++编译器\需要使用某些模式“分解”它们,以对类的名称和这些名称中的参数类型进行编码。 更糟糕的是,每个C ++编译器
brand都使用自己的处理模式。</ p>

因此,我认为虽然 cgo </ code>能够编译C ++代码,但它假设\ 在C ++文件中导出的所有符号(供Go使用)都被
包裹在 extern“ C” {...} </ code>中(请参阅)。</ p>

如果您需要调用“本机” C ++导出的内容,则可以 需要使用
SWIG 。</ p>
< / DIV>

展开原文

原文

I may be wrong, but I think cgo supports C++ only in the sense it knows how to invoke a C++ compiler on the non-Go files which looks like containing C++ source code, and that's all.

The problem is that C++ compilers use so-called "mangling" for the symbols made exported from the compiled files. Exporting symbols were originally intended only for C-like languages, where all which can be exported are plain functions and variables, but C++ adds classes and function overloading, and to export such symbols from compiled ("object") files, a C++ compiler needs to "mangle" them using certain schema to encode names of classes and types of arguments in these names. What's worse, each C++ compiler brand uses its own mangling schemas.

So I think while cgo is able to compile C++ code, it sort of assumes that all the symbols exported (to be used by Go) in your C++ files are wrapped in extern "C" { ... } (see this).

If you need calls to "native" C++ exported stuff, you'd need to use SWIG I reckon.

dongri1989
dongri1989 哦,这很有道理! 非常感谢你的帮助!
3 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐