gpt4 book ai didi

c++ - 从 swig 返回 double * 作为 python 列表

转载 作者:搜寻专家 更新时间:2023-10-31 01:51:13 27 4
gpt4 key购买 nike

我有一个 C++ 类,其中一个方法返回一个类似 double * 的数组,这是它的一个成员变量。我正在尝试将其作为 Python 中的列表进行访问。我将它包装在 doubleArray_frompointer 中,然后尝试使用 deepcopy 将它安全地从那里取出,但是当 doubleArray 超出范围时我仍然遇到问题,它的内存是清理,然后 C++ 类尝试清理相同的内存(尽管这没有在我创建的 gist 中显示)。

我怀疑我应该用类型图来做这件事。

我要包装的是:

double *foo() {
double *toReturn = new double[2];
toReturn[0] = 2;
toReturn[1] = 4;
return toReturn;
}

界面是:

%module returnList
%include "returnList.h"

%include "cpointer.i"
%pointer_functions(double, doubleP)

%include "carrays.i"
%array_class(double, doubleArray);

%{
#include "returnList.h"
%}

最佳答案

您说类型映射可用于避免在 Python 端编写循环是正确的。我举了一个例子 - 它与 this other answer 非常相似.

%module test

%typemap(out) double *foo %{
$result = PyList_New(2); // use however you know the size here
for (int i = 0; i < 2; ++i) {
PyList_SetItem($result, i, PyFloat_FromDouble($1[i]));
}
delete $1; // Important to avoid a leak since you called new
%}

%inline %{
double *foo() {
double *toReturn = new double[2];
toReturn[0] = 2;
toReturn[1] = 4;
return toReturn;
}
%}

这里的类型映射匹配一个名为 foo 的函数返回 double * - 你可以更广泛地匹配,但是对于返回的函数会有做错事情的风险double * 并不意味着您要返回大小为 2 的数组。

有了这个类型图,我就可以运行:

Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> test.foo()
[2.0, 4.0]
>>>

您需要像这样手动编写它的原因是因为 SWIG 无法推断您从 foo 返回的数组的长度。它甚至可能因调用而异。

关于c++ - 从 swig 返回 double * 作为 python 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14033387/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com