将C结构数组转换为numpy数组 [英] Casting an array of C structs to a numpy array
本文介绍了将C结构数组转换为numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从共享库中调用的函数返回的结构类似于以下信息:
A function I'm calling from a shared library returns a structure called info similar to this:
typedef struct cmplx {
double real;
double imag;
} cmplx;
typedef struct info{
char *name;
int arr_len;
double *real_data
cmplx *cmplx_data;
} info;
结构的一个字段是双精度数组,另一个字段是复数数组.如何将复数数组转换为numpy数组?对于双打,我有以下内容:
One of the fields of the structure is an array of doubles while the other is an array of complex numbers. How do I convert the array of complex numbers to a numpy array? For doubles I have the following:
from ctypes import *
import numpy as np
class cmplx(Structure):
_fields_ = [("real", c_double),
("imag", c_double)]
class info(Structure):
_fields_ = [("name", c_char_p),
("arr_len", c_int),
("real_data", POINTER(c_double)),
("cmplx_data", POINTER(cmplx))]
c_func.restype = info
ret_val = c_func()
data = np.ctypeslib.as_array(ret_val.contents.real_data, shape=(info.contents.arr_len,))
是否存在一个用于数字复数的小数线?我可以使用循环来做到这一点.
Is there a numpy one liner for complex numbers? I can do this using loops.
推荐答案
将字段定义为double并使用numpy创建复杂的视图:
Define your field as double and make a complex view with numpy:
class info(Structure):
_fields_ = [("name", c_char_p),
("arr_len", c_int),
("real_data", POINTER(c_double)),
("cmplx_data", POINTER(c_double))]
c_func.restype = info
ret_val = c_func()
data = np.ctypeslib.as_array(ret_val.contents.real_data, shape=(info.contents.arr_len,))
complex_data = np.ctypeslib.as_array(ret_val.contents.cmplx_data, shape=(info.contents.arr_len,2)).view('complex128')
这篇关于将C结构数组转换为numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文