痛饮,返回double数组 [英] Swig, returning an array of doubles

查看:380
本文介绍了痛饮,返回double数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

,经常有许多方法来解决的某些问题。但在这里,我知道我想拥有它哪种方式,但我无法使其与Python和SWIG工作...

I know, there are often many ways to solve certain problems. But here I know which way I want to have it, but I am unable to make it work with Python and SWIG...

我有一个C函数,该函数返回我双倍值的数组:

I have a C-function, which returns me an array of double values:

double *my(int x)
{
   double a,b,*buf;
   buf = malloc (x * sizeof(double));
   a=3.14;
   b=2.7;
   buf[0]=a;
   buf[1]=b;
   return buf;
}

在这里,我明确地希望有数组作为返回值。不,在许多例子无效的功能,这将写入到一个输入数组。现在,我想获得一大口,Python包装,这可能被用来作为:

Here, I definitively want to have the array as a return value. Not, as in many examples a 'void' function, which writes into an input array. Now, I would like to get a SWIG-python wrapper, which might be used as:

>>> import example
>>> print example.my(7)
[3.14,2.7]

无论我做什么,我这里有一些概念上的问题 - 我总是s.th.像<在0xFABCABA12&GT型双*'的痛饮对象;

我想在我的SWG文件来定义一些typemaps:

I tried to define some typemaps in my swg file:

%typemap(out) double [ANY] {
  int i;
  $result = PyList_New($1_dim0);
  for (i = 0; i < $1_dim0; i++) {
    PyObject *o = PyFloat_FromDouble((double) $1[i]);
    PyList_SetItem($result,i,o);
  }
}

不过还是我无法按要求让我的成绩。有没有人有一个简单的code-例子来实现这一任务呢?

But still I am unable to get out my results as required. Does anyone have a simple code-example to achieve this task?

推荐答案

我遭受了类似的问题,解决它的方法如下:

I suffered similar problem and solved it in following way.

// example.i

%module example

%include "carrays.i"
%array_class(float, floatArray);

float * FloatArray(int N);

float SumFloats(float * f);

&NBSP;

# ipython

> a = example.floatArray(23) # array generated by swig's class constructor

> a

<example.floatArray; proxy of <Swig Object of type 'floatArray *' at 0x2e74180> >

> a[0]

-2.6762280573445764e-37 # unfortunately it is created uninitialized..

> b = example.FloatArray(23) # array generated by function

> b

<Swig Object of type 'float *' at 0x2e6ad80>

> b[0]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
# .....
TypeError: 'SwigPyObject' object is not subscriptable

> #But there is a way to access b!!

> p = example.floatArray_frompointer(b) # i found this function by example. and twice tab

> p

<example.floatArray; proxy of <Swig Object of type 'floatArray *' at 0x2e66750> >

> p[0]

0.0

> p[0] = 42

> p[0]

42.0

幸运的是,所有这些类型(浮点*,* floatArray和floatArray *代表)都可以顺利通过,以C ++函数(如SumFloats)。

Fortunately, all of these types (float *, floatArray *, and proxy of floatArray *) may be successfully passed to C++ function (such as SumFloats).

这篇关于痛饮,返回double数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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