I am experimenting with cgo, and wanted to use c++ with cgo. I found this post about doing it. If I have a c++ struct named Foo
and a go struct named Foo
, I want to pass the go Foo
to c++. I tried doing this:
//bind.h
#ifdef __cplusplus
extern "C" {
#endif
#include "structs.hpp"
void bindCgo(Foo bar);
#ifdef __cplusplus
}
#endif
//structs.hpp
#ifndef STRUCTS_HPP_
#define STRUCTS_HPP_
typedef struct Foo {
#ifdef __cplusplus
std::string str;
#endif
}
#endif
//bind.cc
#include "structs.hpp"
using namespace std;
void bindCgo(Foo bar) {
cout << bar.str << endl; //this gives "sΘ\"
}
//main.go
import "unsafe"
// #cgo CFLAGS: -std=c99
// #include "bind.h"
import "C"
type Foo struct {
str string
}
func main() {
bar := Foo{""};
C.bindCgo(((*C.Foo)(unsafe.Pointer(&bar))))
}
Now when I run this program, it gives me sΘ\
. Is this normal, and how can I fix this?
I also have maps and vectors in my struct so using char* will not work