将 C 结构数组转换为 numpy 数组

Casting an array of C structs to a numpy array

我从共享库调用的一个函数returns一个名为 info 的结构类似于:

typedef struct cmplx {
  double real;
  double imag;
} cmplx;

typedef struct info{
  char *name;
  int arr_len;
  double *real_data
  cmplx *cmplx_data;
} info;

结构的一个字段是双精度数组,而另一个字段是复数数组。如何将复数数组转换为 numpy 数组?对于双打,我有以下内容:

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,))

是否有用于复数的 numpy one liner?我可以使用循环来做到这一点。

将你的字段定义为 double 并使用 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')