在新的Go语言中,我如何调用c++代码?换句话说,我如何包装我的c++类并在Go中使用它们?
当前回答
看来这是关于戈朗的一个早期问题。同时回答永不更新。在这三到四年间,有太多的新图书馆和博客文章问世了。下面是我觉得有用的几个链接。
SWIG和Go
使用SWIG调用Go中的c++代码
在比较语言方面,c++和Go
GoForCPPProgrammers
其他回答
您可能需要向Golang/CGo的LDFlags添加-lc++来识别对标准库的需求。
从go1.2+开始,cgo自动合并和编译c++代码:
http://golang.org/doc/go1.2#cgo_and_cpp
从我在FAQ中读到的内容来看,你还不能确定:
Do Go programs link with C/C++ programs? There are two Go compiler implementations, gc (the 6g program and friends) and gccgo. Gc uses a different calling convention and linker and can therefore only be linked with C programs using the same convention. There is such a C compiler but no C++ compiler. Gccgo is a GCC front-end that can, with care, be linked with GCC-compiled C or C++ programs. The cgo program provides the mechanism for a “foreign function interface” to allow safe calling of C libraries from Go code. SWIG extends this capability to C++ libraries.
目前看来,SWIG是最好的解决方案:
https://www.swig.org/Doc4.0/Go.html
它支持继承,甚至允许用Go结构子类化c++类,因此当c++代码中调用重写的方法时,Go代码将被触发。
Go常见问题解答中关于c++的部分更新了,现在提到了SWIG,不再说“因为Go是垃圾收集的,这样做是不明智的,至少是天真的”。
这可以使用命令cgo来实现。
在本质上 如果导入“C”之前紧接着有一个注释,这个注释被称为preamble,在编译包的C部分时被用作头文件。例如:“ 来源:https://golang.org/cmd/cgo/
// #include <stdio.h>
// #include <errno.h>
import "C"
推荐文章
- 我可以列出所有的标准Go包吗?
- decltype(auto)的一些用途是什么?
- Shared_ptr转换为数组:应该使用它吗?
- Printf与std::字符串?
- 在Go中将float64转换为int类型
- 禁用复制构造函数
- 只接受特定类型的c++模板
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c++ 11中的递归lambda函数
- 在c++中指针使用NULL或0(零)吗?
- 在c++中,如何将int值附加到字符串中?
- 就性能而言,使用std::memcpy()还是std::copy()更好?
- 为什么布尔值是1字节而不是1位?
- 四舍五入到一个数字的最接近倍数
- 人们如何在Go中管理身份验证?