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.

balaks
  • 215
  • 1
  • 8
  • 1
    You should not need to convert a double pointer to numpy array. Keep a reference to the original numpy array. – Daniel Aug 25 '16 at 18:33
  • See [here](https://stackoverflow.com/questions/19263879/speeding-up-element-wise-array-multiplication-in-python/19458585#19458585) for an example that realizes this. – Alexander Vogt Aug 25 '16 at 18:44
  • The comments are correct. It all works now. – balaks Sep 05 '16 at 05:18

0 Answers0