1

How should I convert a ctypes pointer back to a numpy array? I am a beginner in both python and fortran - apologies in advance if this is trivial.

Consider the code:

import numpy as np
x = np.array(np.arange(6)) + 0.5
y = x.ctypes.data_as(ctypes.POINTER(ctypes.c_double))

I have taken a numpy array 'x' and converted it into a form suitable for passing into a fortran subroutine as an array 'y'. However, how should I do the reverse operation?

[Q1] Is y is a ctypes pointer? Python says it is <main.LP_c_double at 0x7ff7186178c8>. What does this mean?

[Q2] Starting from y, how can I obtain x, given that I know how long the array x is? I tried:

ctypes.cast(y, ctypes.POINTER(ctypes.c_double)).contents.value

This returns the first element of the array. However, trying to access the next elements using the following failed:

ctypes.cast(y, ctypes.POINTER(ctypes.c_double)).contents.value

Thank you for your help.

3
  • 1
    You should not need to convert a double pointer to numpy array. Keep a reference to the original numpy array. Commented Aug 25, 2016 at 18:33
  • See here for an example that realizes this. Commented Aug 25, 2016 at 18:44
  • The comments are correct. It all works now. Commented Sep 5, 2016 at 5:18

0

Your Answer

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.