从swig返回双*作为python列表
return double * from swig as python list
我有一个c++类,其中一个方法返回一个double *
数组,这是它的一个成员变量。我试着让它在Python中作为一个列表访问。我把它包装在一个doubleArray_frompointer
中,然后尝试使用deepcopy让它安全地离开那里,但是当doubleArray
超出范围时,我仍然有问题,它的内存被清理,然后c++类试图清理相同的内存(尽管这在我创建的要点中没有显示)。
我怀疑我应该用typemaps来做这个。
我想写的是:
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"
%}
你说typemap可以用来避免在Python端编写循环,这是正确的。我把一个例子放在一起——它和另一个答案非常相似。
%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;
}
%}
这里的typemap匹配一个名为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
返回的数组的长度。
我不是通过返回任何类型的向量或数组类对象来"解决"这个问题,而是通过在Python中重新创建最初生成数组的(简单)循环来解决这个问题。也就是说,我的c++代码只需要返回单个双精度对象,而我的Python代码将组装该列表。
稍微显式一点,我有c++方法double *simulation.run()
,这引起了麻烦。我创建了一个新的c++方法double simulation.doRound()
,然后在numRounds
迭代的Python循环中通过SWIG调用它,每次迭代执行outputs.append(simulation.doRound())
。
然而,我仍然想知道如何通过SWIG将C/c++ double *
数组复制到Python列表,因为这似乎是一个基本的操作。如果有人能回答这个问题,我会将其标记为可接受的答案。
- 使用 Main() 返回值作为 python 脚本的参数
- 如何使用 swig C++命名空间作为 python 模块公开
- 调用c++库时,如何在Python中使用ctypes传递字节作为引用
- C++ #include<XXX.h>相当于 Python 导入的 XXX 作为 X
- 我应该把Boost.Python的.so文件放在哪里,这样我就可以把它作为一个模块导入,以及我如何将它与Python 2
- 从C++调用 Python 类方法,如果给定一个初始化的类作为 PyObject
- 将数据从python发送到c ++作为参数或文件?
- 将 python list 作为 'float*' 或 'int*' 传递给 C/C++
- 使用 boost::p ython,如何将结构体向量作为字典列表返回给 Python
- 如何使用 SWIG 将 Python 类实例作为 C++ 函数的参数传递
- 如何使用 Python 实验室机器作为我的C++客户端代码的服务器
- 通过<T> Boost.Python 作为内部引用公开 boost::可选或 None
- 将Boost::Python::object作为参数传递给Python函数
- 传递给C++函数的 Python 整数作为使用 ctypes 的 long 会被截断
- 我可以在 python 类中使用 C++ 类作为超类吗?
- QtCreator拒绝执行自定义python程序作为构建步骤命令
- 如何使python函数作为c++函数的回调
- c++ API作为Python扩展模块
- 为什么C++不能在方便性方面作为Python制作
- 从swig返回双*作为python列表