Last active
December 18, 2015 17:10
-
-
Save DeedleFake/5816947 to your computer and use it in GitHub Desktop.
A little test to try to figure out a way to deal with C++ classes using the new C++ support in CGo.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include "test.h" | |
class Test | |
{ | |
protected: | |
const char *str; | |
public: | |
Test(const char *); | |
~Test(); | |
void print(); | |
}; | |
Test::Test(const char *str) | |
{ | |
this->str = str; | |
} | |
Test::~Test() | |
{ | |
delete[] this->str; | |
} | |
void Test::print() | |
{ | |
std::cout << this->str << std::endl; | |
} | |
void *NewTest(const char *str) | |
{ | |
return new Test(str); | |
} | |
void Test_delete(void *t) | |
{ | |
delete (Test *)t; | |
} | |
void Test_print(void *t) | |
{ | |
((Test *)t)->print(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// #cgo LDFLAGS: -lstdc++ | |
// | |
// #include "test.h" | |
import "C" | |
import ( | |
"runtime" | |
"unsafe" | |
) | |
type Test struct { | |
c unsafe.Pointer | |
} | |
func NewTest(str string) *Test { | |
t := &Test{C.NewTest(C.CString(str))} | |
runtime.SetFinalizer(t, (*Test).free) | |
return t | |
} | |
func (t *Test) free() { | |
C.Test_delete(t.c) | |
} | |
func (t *Test) Print() { | |
C.Test_print(t.c) | |
} | |
func main() { | |
t := NewTest("This is a test.") | |
t.Print() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef TEST_H | |
#define TEST_H | |
#ifdef __cplusplus | |
extern "C" | |
{ | |
#endif | |
void *NewTest(const char *); | |
void Test_delete(void *); | |
void Test_print(void *); | |
#ifdef __cplusplus | |
} | |
#endif | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment