【问题标题】:Iterate `std::vector<std::string>` from Go?从 Go 中迭代`std::vector<std::string>`?
【发布时间】:2021-04-20 14:54:53
【问题描述】:

我正在尝试使用 Go 中的 C++ 库。我对 Go 的经验也很少。

我的 C++ 方法如下所示:

std::vector<std::string> getAttribute(const std::string key);

我的.swigcxx 文件中有这个:

%include "std_string.i"
%include "std_vector.i"

%include "MyCode.h"

%template(StringVector) std::vector<std::string>;

%{
  #include "MyCode.h"
%}

但是 Go 不想让我访问它。我通过以下方式打印了一些信息:

attribs := ipuInfo.GetAttribute("foo")
fmt.Printf("%T\n", attribs)
fmt.Printf("%+v\n", attribs)

我得到:

bar.SwigcptrStringVector
<random number - address perhaps?>

但我不知道如何获取向量的各个内容。我试过了:

for index, val := range bar.GetAttribute("foo") {
}

但这给出了:

cannot range over bar.GetAttribute("foo") (type interface {})

我也尝试过调用.Capacity() 方法,但它没有被声明(来自https://blog.nobugware.com/post/2020/c-bindings-in-go-and-swig/)。我也试过attribs[0],它也不喜欢那样。

有人有什么建议吗?

非常感谢。

【问题讨论】:

  • 做,例如this帮助?
  • 这就是我提到调用.Capacity() 的地方。遗憾的是,它也失败了,因为 CapacityGet 未定义。

标签: c++ go swig


【解决方案1】:

看起来是函数重载的问题。我有 2 个具有相同名称和不同参数的 getAttribute 函数。当我重命名该方法使其独一无二时,Capacity()Get() 工作(尽管 range 不工作)。

看起来 Swig 试图生成包装器代码来调用正确的方法,但无法处理不同的返回类型

【讨论】:

  • range 在 Go 中仅为内置的可迭代类型(切片、数组、映射、通道、字符串)定义。不能用于接口值。
猜你喜欢
  • 1970-01-01
  • 2017-02-01
  • 2014-11-08
  • 2012-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-13
  • 1970-01-01
相关资源
最近更新 更多