如何在 Python 中将指针传递给包装的 C++ 函数的数组
-
06-09-2019 - |
题
我是 C++/Python 混合语言编程的新手,对 Python/C API 没有太多了解。我刚刚开始使用 Boost.Python 来包装 Python 的 C++ 库。我坚持包装一个将指向数组的指针作为参数的函数。以下 (2nd ctor) 是其 C++ 原型。
class AAF{
AAF(AAF_TYPE t);
AAF(double v0, const double * t1, const unsigned * t2, unsigned T);
~AAF();
}
我把它像这样包装在 boost::python 中做得对吗?
class_<AAF>("AAF", init<AAF_TYPE>())
.def(init<double, const double*, const unsigned*, unsigned>());
请注意,它编译并链接成功,但我不知道如何在 Python 中调用它。我天真的尝试如下失败了。
>>> z = AAF(10, [4, 5.5, 10], [1, 1, 2], 3);
Traceback (most recent call last):
File "./test_interval.py", line 40, in <module>
z = AAF(10, [4, 5.5, 10], [1, 1, 2], 3);
Boost.Python.ArgumentError: Python argument types in
AAF.__init__(AAF, int, list, list, int)
did not match C++ signature:
__init__(_object*, AAF_TYPE)
__init__(_object*, double, double const*, unsigned int const*, unsigned int)
>>> t1 = array.array('d', [4, 5.5, 10])
>>> t2 = array.array('I', [1, 1, 2])
>>> z = AAF(10, t1, t2, 3);
Traceback (most recent call last):
File "./test_interval.py", line 40, in <module>
z = AAF(10, t1, t2, 3);
Boost.Python.ArgumentError: Python argument types in
AAF.__init__(AAF, int, array.array, array.array, int)
did not match C++ signature:
__init__(_object*, AAF_TYPE)
__init__(_object*, double, double const*, unsigned int const*, unsigned int)
我的第二个问题是我还需要包装析构函数吗?请指定在某些情况下是否需要这样做,但并非总是如此。
解决方案
包装是正确的(原则上),但在
AAF(10, [4, 5.5, 10], [1, 1, 2], 3);
(正如解释器指出的)你传递给函数的是 python 的列表对象,而不是指针。
简而言之,如果您的函数只需要在 python 列表上工作,您需要更改代码以使用该接口(而不是使用指针)。如果您需要保留该接口,则必须编写一个包装函数,该函数从 python 中获取列表,进行正确的转换并调用原始的 C++ 函数。这同样适用于 numpy 数组。
请注意,boost::python 提供了一些内置机制将 python 容器转换为 stl 兼容容器。
您的案例的包装代码示例可能是
void f(list o) {
std::size_t n = len(o);
double* tmp = new double[n];
for (int i = 0; i < n; i++) {
tmp[i] = extract<double>(o[i]);
}
std::cout << std::endl;
// use tmp
delete tmp;
}
请查看 boost.python 教程: http://www.boost.org/doc/libs/1_39_0/libs/python/doc/tutorial/doc/html/index.html.
不隶属于 StackOverflow