0

I am new to C and ctypes in Python.

I need to convert a C pointer to an array of doubles into a Python numpy array.

I have the following starting point:

import ctypes
import numpy as np
arrayPy = np.array([[0, 1, 2], [3, 4, 5]])
out_c = arrayPy.ctypes.data_as(ctypes.POINTER(ctypes.c_double))

May I ask how I can efficiently convert the "out_c" object to a Python numpy array?

Riccardo Bucco
15.5k4 gold badges29 silver badges57 bronze badges
asked Nov 25, 2021 at 11:31

1 Answer 1

1

The starting point is incorrect since arrayPy is an array of integers. Set the dtype to make an array of doubles:

import ctypes
import numpy as np
arrayPy = np.array([[0, 1, 2], [3, 4, 5]], dtype=ctypes.c_double)
out_c = arrayPy.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
print(out_c, out_c[:arrayPy.size])

Output is a C pointer to double. Slicing the pointer will show the data, but you need to know the size to not iterate past the end of the data:

<__main__.LP_c_double object at 0x000001A2B758E3C0> [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]

I need to convert a C pointer to an array of doubles into a Python numpy array.

To convert that pointer back to a numpy array, you can use the following if you know its shape:

a = np.ctypeslib.as_array(out_c, shape=arrayPy.shape)
print(a)

Output:

[[0. 1. 2.]
 [3. 4. 5.]]
answered Nov 26, 2021 at 17:49
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This approach solves my problem.

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.