【发布时间】: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 数组由
objects的Ohlc组成,它基本上是一个指针/参考。我在 C++ 方面真正需要的是所谓的structured/recordnumpy 数组和 python 端代码将需要更改。但我仍然不知道如何正确指定 py 绑定。