Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use c++ in cgo?

Tags:

c++

go

cgo

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

like image 756
Chris_F Avatar asked Jul 10 '12 04:07

Chris_F


1 Answers

@ephemient provided a link to the feature request for this in the Go bug tracker. That in turn provided a link back to How to use C++ in Go? 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.

  2. The link to The SWIG documentation for Go.

like image 126
Darshan Rivka Whittle Avatar answered Oct 04 '22 19:10

Darshan Rivka Whittle