簡體   English   中英

如何通過 pybind11 調用 numpy 用戶定義結構數組的 C++ API

[英]How to call C++ API with numpy array of user defined structs via pybind11

我瀏覽了文檔並在互聯網上進行了很多搜索,但找不到任何解決方案。 這是相關的代碼片段

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 個Ohlc而不是數組。 不確定它是否是缺少的功能或錯誤,或者很可能是我的代碼中缺少的東西。 請指教。

請參閱此處有關將數據分配給結構化數組的部分。 您可以傳遞表示 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 嘗試分配給各個字段,而不是數據類型本身。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM