英文:
Can I use c++ in cgo?
问题
在cgo中是否可以混合一些C++代码?
我尝试了这个:
package main
/*
#include <iostream>
extern "C" void test(const char* str)
{
std::cout << str;
}
*/
// #cgo CFLAGS: -x c++
// #cgo LDFLAGS: -lstdc++
import "C"
func main() {
C.test(C.CString("Testing!!!"))
}
但是我得到了以下错误:
error: 'char* CString(_GoString_)' cannot appear in a constant-exp
error: 'void test(const char*)&' cannot appear in a constant-expres
error: invalid conversion from 'char* (*)(_GoString_)' to 'long long int' [-fpermissive]
error: invalid conversion from 'void (*)(const char*)&' to 'long long int' [-fpermissive]
我正在使用go1.0.2和MinGW-w64 4.7.1
英文:
Is it possible to mix in some C++ code in cgo?
I tried this:
package main
/*
#include <iostream>
extern "C" void test(const char* str)
{
std::cout << str;
}
*/
// #cgo CFLAGS: -x c++
// #cgo LDFLAGS: -lstdc++
import "C"
func main() {
C.test(C.CString("Testing!!!"))
}
But I get these errors:
error: 'char* CString(_GoString_)' cannot appear in a constant-exp
error: 'void test(const char*)' cannot appear in a constant-expres
error: invalid conversion from 'char* (*)(_GoString_)' to 'long long int' [-fpermissive]
error: invalid conversion from 'void (*)(const char*)' to 'long long int' [-fpermissive]
I'm using go1.0.2 and MinGW-w64 4.7.1
答案1
得分: 11
@ephemient在Go bug跟踪器中提供了一个功能请求的链接。这反过来提供了一个链接回到Stack Overflow上的https://stackoverflow.com/questions/1713214/how-to-use-c-in-go/1721230。那里有一个很好的讨论,但对我来说要点是:
-
链接到Go FAQ(Go程序是否与C/C++程序链接?):
... cgo程序提供了一种“外部函数接口”的机制,允许从Go代码安全地调用C库。SWIG将此功能扩展到C++库。
-
链接到Go的SWIG文档。
英文:
@ephemient provided a link to the feature request for this in the Go bug tracker. That in turn provided a link back to https://stackoverflow.com/questions/1713214/how-to-use-c-in-go/1721230 here on Stack Overflow. There's a good discussion there, but the takeaways for me were:
- The link to the Go FAQ (Do Go programs link with C/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.
- The link to The SWIG documentation for Go.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论