将swig python'double *'对象读入numpy(也许通过ctypes吗?) [英] Read swig python 'double *' object into numpy (maybe through ctypes?)

查看:132
本文介绍了将swig python'double *'对象读入numpy(也许通过ctypes吗?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有无法修改的Swig python库.

I have swig python library that I can't modify.

它返回一个<Swig object of type 'double *'>,我知道这是一个指向双精度数组的指针.通过一个单独的函数,我得到了一个python int的长度.

It returns a <Swig object of type 'double *'> which I know is a pointer to an array of doubles. Through a separate function, I get a python int for the length.

我的问题是,如何将这些数据读入numpy?

My question is, how can I read this data into numpy?

我已经找到了numpy.ndarray.ctypes模块,还有另一个stackoverflow答案,提示可能从SWIG转换为ctypes( https://stackoverflow.com/a/41212424/654602 ),但没有提及如何操作.

I've found the numpy.ndarray.ctypes module, and another stackoverflow answer that hints that a conversion from SWIG to ctypes is possible (https://stackoverflow.com/a/41212424/654602) but makes no mention how.

感谢您的帮助.

推荐答案

我创建了一个示例SWIG包装器来对此进行测试:

I created a sample SWIG wrapper to test this:

%module test

%{
#include <stdlib.h>
#include <stdio.h>

double* get(void)
{
    double* p = malloc(sizeof(double) * 10);
    for(int i = 0; i < 10; ++i)
        p[i] = 1.1 * i;
    printf("%p\n",p);
    return p;
}
%}

double* get(void);

以下内容通过ctypes检索数据:

The following retrieves the data via ctypes:

>>> import test
>>> a = test.get()
000001A3D05ED890        # From the printf...
>>> a
<Swig Object of type 'double *' at 0x000001A3D27D6030>
>>> hex(int(a))
'0x1a3d05ed890'         # int() of the object is the same address
>>> from ctypes import *
>>> p = (c_double * 10).from_address(int(a))
>>> list(p)
[0.0, 1.1, 2.2, 3.3000000000000003, 4.4, 5.5, 6.6000000000000005, 7.700000000000001, 8.8, 9.9]

现在为numpy.也许有更好的方法,但是我发现__array_interface__(

Now for numpy. There may be a better way, but I found __array_interface__ (link). An "array-like" object has this interface and another array can be created from it:

>>> class Tmp: pass
...
>>> Tmp.__array_interface__ = {'shape':(10,),'typestr':'<f8','data':(int(a),False),'version':3}
>>> import numpy as np
>>> np.array(Tmp,copy=False)   # Create array that shares the same interface
array([0. , 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])

也许不是最好的方法,但我不是numpy的重度用户.

Maybe not the best way, but I'm not a heavy user of numpy.

这篇关于将swig python'double *'对象读入numpy(也许通过ctypes吗?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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