1
1
12rbah2021-08-16 17:24:52
go
12rbah, 2021-08-16 17:24:52

How to properly initialize a c++ structure in go via cgo?

I'm trying to deal with cgo, I'm trying to return an initialized structure from c++ code, but only a null pointer is returned, what am I doing wrong?

//wrapper.cpp
struct Something
{
    int nValue;
    float fValue;
};

void* retSome(){
    Something s;
    s.fValue = 5;
    s.nValue = 2;
    return static_cast<void*>(&s);
}

// wrapper.h
#ifdef __cplusplus
extern "C" {
#endif

void print();
void print2();
void* setString(const char *name);
void* setStringUnsafe(void*);
void* retSome();
#ifdef __cplusplus
}
#endif

//cgo.go
type Something struct
{
  nValueint int
  fValue float64
}

func main() {
  ptr := C.retSome()
  var s = new(Something)
  s = (*Something)(unsafe.Pointer(ptr))

  fmt.Println(ptr,s) //nil nil 
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question