python定义数组是带指针_如何在Python中为包装的C函数传递指向数组的指针

我是C / Python混合语言编程的新手,对Python / C API不太了解.我刚开始使用Boost.Python为Python包装一个C库.我被困在包装一个函数,该函数将指向数组的指针作为参数.以下(第二个ctor)是它在C中的原型.

class AAF{

AAF(AAF_TYPE t);

AAF(double v0, const double * t1, const unsigned * t2, unsigned T);

~AAF();

}

我是通过在boost :: python中这样包装它来做的吗?

class_("AAF", init())

.def(init());

请注意,它已成功编译和链接,但我无法弄清楚如何在Python中调用它.我的天真尝试如下失败.

>>> z = AAF(10, [4, 5.5, 10], [1, 1, 2], 3);

Traceback (most recent call last):

File "./test_interval.py", line 40, in

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

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(o[i]);

}

std::cout << std::endl;

// use tmp

delete tmp;

}

标签:python,arrays,pointers,wrapping,boost-python

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值