Skip to content

Instantly share code, notes, and snippets.

@DeedleFake
Last active December 18, 2015 17:10
Show Gist options
  • Save DeedleFake/5816947 to your computer and use it in GitHub Desktop.
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.
#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();
}
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()
}
#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