首页 > 解决方案 > CGO,将结构从 go 传递到 c++

问题描述

我正在尝试使用 cgo,并希望将 c++ 与 cgo 一起使用。我发现这篇文章是关于这样做的。如果我有一个名为的 c++ 结构Foo和一个名为的 go 结构Foo,我想将 go 传递Foo给 c++。我试过这样做:

//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))))
}

现在当我运行这个程序时,它给了我sΘ\. 这是正常的,我该如何解决这个问题?

我的结构中也有地图和向量,因此使用 char* 将不起作用

标签: c++cgostructcgo

解决方案


推荐阅读