Skip to content
This repository was archived by the owner on Jan 6, 2018. It is now read-only.

Commit f23a824

Browse files
committed
Initial
0 parents  commit f23a824

File tree

7 files changed

+104
-0
lines changed

7 files changed

+104
-0
lines changed

Makefile

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
.PHONY: clean default
2+
3+
default: libfoo.a
4+
go build .
5+
6+
libfoo.a: foo.o cfoo.o
7+
ar r libfoo.a foo.o cfoo.o
8+
9+
cfoo.o: cfoo.cpp
10+
g++ -fPIC -O2 -o cfoo.o -c cfoo.cpp
11+
12+
foo.o: foo.cpp
13+
g++ -fPIC -O2 -o foo.o -c foo.cpp
14+
15+
clean:
16+
rm -f *.o *.so *.a test

README.md

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Wrapping C++ with Go
2+
3+
This is a minimal example of how to wrap a C++ class manually with Go.
4+
5+
I borrowed most of the code from [a stack overflow answer](http://stackoverflow.com/questions/1713214/how-to-use-c-in-go),
6+
but modified it to use static linking.
7+

cfoo.cpp

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#include "foo.hpp"
2+
#include "foo.h"
3+
4+
Foo FooInit() {
5+
cxxFoo * ret = new cxxFoo(1);
6+
return (void*)ret;
7+
}
8+
9+
void FooFree(Foo f) {
10+
cxxFoo * foo = (cxxFoo*)f;
11+
delete foo;
12+
}
13+
14+
void FooBar(Foo f) {
15+
cxxFoo * foo = (cxxFoo*)f;
16+
foo->Bar();
17+
}
18+

foo.cpp

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#include <iostream>
2+
#include "foo.hpp"
3+
4+
void cxxFoo::Bar(void) {
5+
std::cout<<this->a<<std::endl;
6+
}
7+

foo.go

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package main
2+
3+
// #cgo LDFLAGS: -lfoo
4+
// #include "foo.h"
5+
import "C"
6+
7+
type GoFoo struct {
8+
foo C.Foo
9+
}
10+
11+
func New() GoFoo {
12+
var ret GoFoo
13+
ret.foo = C.FooInit()
14+
return ret
15+
}
16+
func (f GoFoo) Free() {
17+
C.FooFree(f.foo)
18+
}
19+
func (f GoFoo) Bar() {
20+
C.FooBar(f.foo)
21+
}
22+
23+
func main() {
24+
foo := New()
25+
foo.Bar()
26+
foo.Free()
27+
}

foo.h

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#ifndef _MY_PACKAGE_FOO_H_
2+
#define _MY_PACKAGE_FOO_H_
3+
4+
#ifdef __cplusplus
5+
extern "C" {
6+
#endif
7+
8+
typedef void* Foo;
9+
Foo FooInit(void);
10+
void FooFree(Foo);
11+
void FooBar(Foo);
12+
13+
#ifdef __cplusplus
14+
}
15+
#endif
16+
17+
#endif

foo.hpp

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#ifndef _MY_PACKAGE_FOO_HPP_
2+
#define _MY_PACKAGE_FOO_HPP_
3+
4+
class cxxFoo {
5+
public:
6+
int a;
7+
cxxFoo(int _a):a(_a){};
8+
~cxxFoo(){};
9+
void Bar();
10+
};
11+
12+
#endif

0 commit comments

Comments
 (0)