【问题标题】:How to call C++ API with numpy array of user defined structs via pybind11如何通过 pybind11 使用用户定义结构的 numpy 数组调用 C++ API
【发布时间】:2021-12-31 07:38:45
【问题描述】:

我浏览了文档并在互联网上进行了很多搜索,但找不到任何解决方案。这里是相关代码sn-p

struct Ohlc {
    double open, high, low, close;
    int volume;
};

using array_dtype = Ohlc;

void calculate_ema_pyarray(const py::array_t<const array_dtype,
     py::array::c_style | py::array::forcecast> array) {
 // DO something with array
}

PYBIND11_MODULE(ema_calculator_pybind11, m) {
  // optional module docstring
  m.doc() = "pybind11 plugin for ema calculations";

  py::class_<Ohlc>(m, "Ohlc")
      .def(py::init<>())
      .def_readwrite("open", &Ohlc::open)
      .def_readwrite("high", &Ohlc::high)
      .def_readwrite("low", &Ohlc::low)
      .def_readwrite("close", &Ohlc::close);

     PYBIND11_NUMPY_DTYPE(Ohlc, open, high, low, close);

  m.def("calculate_ema", &calculate_ema_pyarray,
     "Calculates EMA for given input");
}

以下是我在 python 中使用时遇到的错误

>>> from ema_calculator_pybind11 import *
>>> import numpy as np
>>> calculate_ema(np.array([Ohlc()]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: calculate_ema(): incompatible function arguments. The following argument types are supported:
    1. (arg0: numpy.ndarray[ema_calculator_pybind11.Ohlc]) -> None

Invoked with: array([<ema_calculator_pybind11.Ohlc object at 0x7f926d284670>],
      dtype=object)

如果我将 array_dtype 更改为内置类型,则上述方法有效,例如using array_dtype = double; 或者如果我只取 Ohlc 的 1 个对象而不是数组。 不确定它是否是缺少的功能或错误,或者很可能是我的代码中缺少的东西。请指教。

【问题讨论】:

  • 您是否尝试过像 np.array([Ohlc()], dtype=ema_calculator_pybind11.Ohlc) 这样创建数组?
  • 您是否尝试仅使用小写字母,例如ohlc 而不是 Ohlc?我曾经遇到过类似的问题,在使用pybind11时让我发疯...
  • dtype=ema_calculator_pybind11.Ohlc 相同的错误。带有 ohlc 的错误是 NameError: name 'ohlc' is not defined
  • 我遇到的可能与此处相关的新事物似乎是我在上面定义和绑定东西的方式,numpy 数组由objectsOhlc 组成,它基本上是一个指针/参考。我在 C++ 方面真正需要的是所谓的structured/record numpy 数组和 python 端代码将需要更改。但我仍然不知道如何正确指定 py 绑定。

标签: python c++ numpy pybind11


【解决方案1】:

请参阅将数据分配给结构化数组here 的部分。您可以传递表示 dtype 中每个字段的值的元组列表,例如

from ema_calculator_pybind11 import *
import numpy as np
calculate_ema(np.array([
    (1.0, 1.2, 0.9, 1.05, 100),
    (100.0, 150.0, 90.0, 100.0, 200)
], dtype=Ohlc))

numpy 尝试分配给各个字段,而不是数据类型本身。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-15
    • 2020-02-29
    • 2017-11-23
    • 2016-09-29
    • 1970-01-01
    • 2022-12-25
    • 2019-01-16
    • 2015-12-18
    相关资源
    最近更新 更多