return double * from swig as python list [英] return double * from swig as python list

查看:212
本文介绍了return double * from swig as python list的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++类,其中的一个方法返回一个 double * 数组类似的,它的一个成员变量。我试图使这个作为列表在Python中可访问。我把它包装在一个 doubleArray_frompointer ,然后尝试使用deepcopy安全地从它出来,但我仍然有问题,当 doubleArray 超出范围,它的内存被清理,然后C ++类试图清理相同的内存(虽然这没有显示在 gist 我创建了)。

I have a C++ class, one of whose methods returns a double * array-like that is one of its member variables. I'm trying to make this accessible as a list in Python. I wrap it in a doubleArray_frompointer, and then try using deepcopy to get it out of there safely, but I still have problems when the doubleArray goes out of scope, its memory is cleaned up, and then the C++ class tries to clean up the same memory (although that's not shown in the gist I created).

我怀疑我应该使用typemaps。

I suspect I should be doing this with 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端写一个循环。我举了一个例子 - 它非常类似于这个其他答案

You're correct in saying that a typemap can be used to avoid writing a loop on the Python side. I put together an example - it's pretty similar to 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;
}
%}

此处的typemap与 foo 返回 double * - 你可以匹配更广泛,但是会有一个风险, code> double * 并不表示您要传回的大小为2的数组。

The typemap here matches a function called foo returning double * - you could match more widely but then there would be a risk of doing the wrong thing for functions where returning double * doesn't mean you're returning an array of size 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 返回的数组的长度。它甚至可能在不同的电话之间。

The reason you need to write it manually like this is because there is no way for SWIG to infer the length of the array that you are returning from foo. It could even vary between calls.

这篇关于return double * from swig as python list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆