我可以在cgo中使用C++吗?

huangapple go评论88阅读模式
英文:

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 &lt;iostream&gt;

    extern &quot;C&quot; void test(const char* str)
    {
        std::cout &lt;&lt; str;
    }
*/
// #cgo CFLAGS: -x c++
// #cgo LDFLAGS: -lstdc++
import &quot;C&quot;

func main() {
    C.test(C.CString(&quot;Testing!!!&quot;))
}

But I get these errors:

error: &#39;char* CString(_GoString_)&#39; cannot appear in a constant-exp
error: &#39;void test(const char*)&#39; cannot appear in a constant-expres
error: invalid conversion from &#39;char* (*)(_GoString_)&#39; to &#39;long long int&#39; [-fpermissive]
error: invalid conversion from &#39;void (*)(const char*)&#39; to &#39;long long int&#39; [-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。那里有一个很好的讨论,但对我来说要点是:

  1. 链接到Go FAQ(Go程序是否与C/C++程序链接?):

    ... cgo程序提供了一种“外部函数接口”的机制,允许从Go代码安全地调用C库。SWIG将此功能扩展到C++库。

  2. 链接到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:

  1. 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.

  1. The link to The SWIG documentation for Go.

huangapple
  • 本文由 发表于 2012年7月10日 12:52:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/11406812.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定