Skip to content

Instantly share code, notes, and snippets.

@fis
Last active June 21, 2022 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fis/9a35407472b51dbda15f259826223983 to your computer and use it in GitHub Desktop.
Save fis/9a35407472b51dbda15f259826223983 to your computer and use it in GitHub Desktop.
CGo C++ test
// mylib.c
#include "mylib.hh"
#include "cmylib.h"
Foo FooInit()
{
cxxFoo * ret = new cxxFoo(1);
return (void*)ret;
}
void FooFree(Foo f)
{
cxxFoo * foo = (cxxFoo*)f;
delete foo;
}
void FooBar(Foo f)
{
cxxFoo * foo = (cxxFoo*)f;
foo->Bar();
}
// mylib.h
#ifdef __cplusplus
extern "C" {
#endif
typedef void* Foo;
Foo FooInit(void);
void FooFree(Foo);
void FooBar(Foo);
#ifdef __cplusplus
}
#endif
module example.com/test
go 1.18
#include <iostream>
#include "mylib.hh"
void cxxFoo::Bar(void){ std::cout << "hello\n"; }
class cxxFoo {
public:
int a;
cxxFoo(int _a):a(_a){};
~cxxFoo(){};
void Bar();
};
package main
// #cgo LDFLAGS: -Llib -lmylib_a
// #cgo CPPFLAGS: -Ilib
// #include "cmylib.h"
import "C"
import (
"unsafe"
)
type GoFoo struct {
foo C.Foo
}
func New() (GoFoo) {
var ret GoFoo;
ret.foo = C.FooInit()
return ret
}
func (f GoFoo) Free(){
C.FooFree(C.Foo(unsafe.Pointer(f.foo)))
}
func (f GoFoo) Bar(){
C.FooBar(C.Foo(unsafe.Pointer(f.foo)))
}
func main() {
mylib := New()
mylib.Bar()
mylib.Free()
}
$ cd lib
lib$ g++ -c -o mylib.o mylib.cc
lib$ ar -crs libmylib_a.a mylib.o
lib$ cd ..
$ go run .
hello
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment