doufocheng6233 2017-02-15 17:59
浏览 175
已采纳

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!

  • 写回答

1条回答 默认 最新

  • dongsheng1698 2017-02-16 08:30
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题