Skip to content
Advertisement

ndpointer in ctypes structure field

I cannot figure out how to use numpy.ndpointer as a field in a python ctypes structure. Here is some basic code, showing how I can do this without using ndpointer, but I would like to know if it’s possible to use ndpointer as well if it’s possible!

JavaScript

Using the above code this works fine

JavaScript

But when I call this, I get the following error message

JavaScript
JavaScript

Advertisement

Answer

Listing [Python.Docs]: ctypes – A foreign function library for Python.

According to [NumPy]: numpy.ctypeslib.ndpointer(dtype=None, ndim=None, shape=None, flags=None) (emphasis is mine):

An ndpointer instance is used to describe an ndarray in restypes and argtypes specifications.

argtypes and restype only have meaning in the context of a function (call), and that is when ndpointer should be used (exemplified in the URL).

As a workaround, you can have an ndpointer structure member, but you have to initialize it in the same manner as the ctypes.POINTER one (in MyStruct_Working). However, bear in mind that this will come with some limitations (you won’t have indexing) afterwards.
My suggestion is to stick with ctypes.POINTER(ctypes.c_double).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement