8

是否可以在 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

4

1 回答 1

11

@ehemient 在 Go 错误跟踪器中提供了指向此功能请求的链接。这反过来又提供了一个链接到如何在 Go 中使用 C++?在这里堆栈溢出。那里有一个很好的讨论,但对我来说,要点是:

  1. Go FAQ 的链接(Do Go 程序与 C/C++ 程序链接吗?):

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

  2. Go 的 SWIG 文档的链接。

于 2012-07-10T05:59:02.930 回答