0

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;

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.

asked Oct 15, 2016 at 19:04

1 Answer 1

2

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')
answered Oct 15, 2016 at 19:15
Sign up to request clarification or add additional context in comments.

4 Comments

The shared library requires that the field be a pointer to the cmplx struct.
Ok, that did work. Could you please explain why? C requires it to be a pointer to the cmplx struct but we're using a pointer to a c_double object in python.
a complex number is nothing else, than two doubles. For the interface, the type is not important (you can even use bytes). In the end, the view of your numpy-array defines the type.
I see. Thank you so much for your help!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.