This is a creation in Article, where the information may have evolved or changed.
Update: I ' ve succeeded in linking a small test C + + class with Go
If you wrap your C + + code with a C interface should is able to call your library with CGO (see the example of GMP in $G OROOT/MISC/CGO/GMP).
I ' m not sure if the idea of a class in C + + is really expressible in go, as it doesn ' t has inheritance.
Here's an example
I have a C + + class defined as
//FOO.HPPclassCxxfoo{ Public: inta;Cxxfoo(int_a):a(_a){}; ~Cxxfoo(){}; void Bar();};//Foo.cpp#include <iostream>#include "FOO.HPP"voidCxxfoo::Bar(void){STD::cout<< This -a<<STD::Endl;}
Which I want to use in go. I ' ll use the C interface
//Foo.h#ifdef__cplusplusextern "C" {#endif typedef void* Foo; Foo Fooinit(void); void Foofree(Foo); void FooBar(Foo);#ifdef__cplusplus}#endif
(I use a void* instead of a C struct so the compiler knows the size of Foo)
The implementation is
//cfoo.cpp#include "FOO.HPP"#include "Foo.h"Foo Fooinit(){Cxxfoo*ret= NewCxxfoo(1); return (void*)ret;}void Foofree(FooF){Cxxfoo*Foo= (Cxxfoo*)F; DeleteFoo;}void FooBar(FooF){Cxxfoo*Foo= (Cxxfoo*)F;Foo -Bar();}
With all, and the go file is
//Foo.goPackage Foo//#include "foo.h"Import "C"Import "unsafe"typeGofoo struct {Foo C.Foo;}funcNew()(Gofoo){var retGofoo;ret.Foo=C.Fooinit(); returnret;}func(FGofoo) Free(){C.Foofree(unsafe.Pointer(F.Foo));}func(FGofoo)Bar(){C.FooBar(unsafe.Pointer(F.Foo));}
The makefile I used to compile this is
//MakefileTarg=Foocgofiles=Foo.Goinclude $(Goroot)/src/ Make.$(Goarch)include $(Goroot)/src/ Make.Pkgfoo.o:Foo.CPP G++ $(_cgo_cflags_$(Goarch)) -FPIC-O2-o $@-C $(Cgo_cflags) $<Cfoo.o:Cfoo.CPP G++ $(_cgo_cflags_$(Goarch)) -FPIC-O2-o $@-C $(Cgo_cflags) $<Cgo_ldflags+=-LSTDC++$(Elem)_foo. So:Foo.Cgo4.o foo.o cfoo.o gcc $(_cgo_cflags_$(Goarch)) $(_cgo_ldflags_$(GOOS)) -o $@ $^ $(Cgo_ldflags)
Try testing it with
//foo_test.go package foo import "testing" func Testfoo ( t * Testing t foo := Span class= "Typ" >new (); foo bar (); foo free (); }
You'll need to install the shared library with make install and then run make test. Expected output is
GOTESTRM-F _test/Foo.a _gotest_.66g -o _gotest_.6Foo.Cgo1.go foo.Cgo2.Go foo_test.Gorm-F _test/Foo.Agopack GRC _test/Foo.a _gotest_.6Foo.Cgo3.61PASS