c++ - 在 Go (golang) 和 C++ 之间交换数据结构(数组)

标签 c++ arrays go wrapper cgo

我正在尝试将 C++ 库连接到用 Go 编写的应用服务器。目标是 C++ 库和应用程序服务器都在共同的数据结构上工作,这意味着:

  1. Go 应用服务器可以访问由 C++ 库创建的数组。
  2. C++ 库可以处理由 Go 应用服务器创建的数组。

我正在尝试使用 cgo 并连接 C++,到目前为止一切正常......但是,当涉及到交换数据结构指针时,我迷路了。到目前为止我尝试了什么:

//c++ library header: xyz.h

#include <stdlib.h>

class CppLib {
 public:
  CppLib(unsigned int input);

  int * CreateArray();
};

//C++ library implementation: xyz.cpp
#include "xyz.h"

CppLib::CppLib(unsigned int input) {
    _input = input;
  }

int * CppLib::CreateArray() {
    int values = 5;
    int * myPointer = new int [values];
    for (unsigned i = 0; i < values; ++i) {
        myPointer[i] = i;
    }
    return myPointer;
}

接口(interface)实现如下:

//interface.h

int * CCreateArray();

//interface.cc
#include "../lib/xyz.h"

extern "C" {

  int * CCreateArray() {
    CppLib lib(1);
    return lib.CreateArray();
  }
}

最终的 go 实现如下所示:

package cgo_lib

// #cgo CFLAGS: -I../lib
// #cgo LDFLAGS: -L../lib -linterfacelib
// #include "interface.h"
import "C"

func GoCreateArray() *int {
    return *int(C.CCreateArray())
}

编译时出现以下错误:

# cgo_lib
../cgo_lib/cgo_lib.go:13: cannot convert _Cfunc_CCreateArray() (type *C.int) to type int
../cgo_lib/cgo_lib.go:13: invalid indirect of int(_Cfunc_CCreateArray()) (type int)

所以我的问题是:如何在 C++ 和 Go 之间交换指向数据结构的指针。上面我只是描述了从 C++ 到 GO 的方式,但我也对反过来的方式感兴趣。

非常感谢您的提前帮助。

最佳答案

这里是:

return *int(C.CCreateArray())

可以写成

return *((int)(C.CCreateArray()))

您正在取消引用 int,这会导致:

invalid indirect of int(_Cfunc_CCreateArray()) (type int)

在该语句中,仅观察这部分:

(int)(C.CCreateArray())

您正在尝试将 *C.int 转换为 int,这不会起作用,因为第一个是指针而第二个不是。

除此之外,还有@tadman 在您的问题的评论中提到的内存管理问题,Go 并不像 C 那样将数组表示为指向其第一个元素的指针。

如果你想共享 int,你必须具体说明它们的宽度:Go 中的 int 具有依赖于架构的宽度,以及C int.

阅读更多关于 CGO 的信息:http://golang.org/cmd/cgo/

一旦你解决了所有这些问题,你就必须继续这样的事情:

s := make([]int32, 0, 0)

h := (*reflect.SliceHeader)((unsafe.Pointer)(&s))

h.Data, h.Len, h.Cap = P, L, L // see below

s = *(*[]int32)(h)

其中 P 是您的数组的 Go uintptr,它是您在 C++ 中创建的,L 是 Go 中数组的长度int

关于c++ - 在 Go (golang) 和 C++ 之间交换数据结构(数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28566242/

相关文章:

c++ - 用于 C++ 的基于行的线程安全 std::cerr

c++ - 无法在 Windows 8 的 Cygwin 上编译基本的 C++ 程序

java - 如何从 List<Object> 中检索每个值

javascript - 如何将查询结果传递给javascript

javascript - 使用此 .length & .split() 的任何替代方法?

Golang io.Pipe 与 node.js 管道

c++ - 将 mysql_row 转换为整数

go - 获取在 Go 中执行函数所花费的时间

go - 使用 []string 字段时出现无法比较的类型错误(Go lang)

c++ - 无法将本地编译的库添加到 CMake 项目