Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ctypes how to read array from a void pointer return

Tags:

python

ctypes

So I am trying to read an unsigned short array which is returned by a void pointer in the c library I am using. The function definition in the header is like this:

void* Foo(int a, int b)

This function end up returning an a pointer to an array of type unsigned short.

In python I have been trying to return the array using ctypes without success. Here is what I have:

import ctypes
import numpy as np

libc = ctypes.cdll.LoadLibrary("Library.dll")

Vec=np.zeros((1000,),dtype=np.uint16)

c_ushort_p = ctypes.POINTER(ctypes.c_ushort)
Vec_p=confVec.ctypes.data_as(c_ushort_p)

libc.Foo.restype = ctypes.c_void_p
Vec_p=libc.Foo(1,1)

print Vec_p

This returns "None".

If I try:

...
libc.Foo.restype = ctypes.c_void_p
Vec_p=libc.Foo(1,1)

print Vec_p[0]

I get TypeError: 'NoneType' object has no attribute 'getitem'.

I also tried this:

...
libc.Foo.restype = ctypes.c_void_p
Vec_p=ctypes.cast(libc.Foo(1,1),c_ushort_p)

print Vec_p

Which returns , where print Vec_p[0] gives "ValueError: NULL pointer access"

Can anyone give me any assistance?

like image 294
Wilsonator Avatar asked Jul 04 '26 19:07

Wilsonator


1 Answers

The DLL is returning a null pointer. These are represented as None in ctypes.

I don't know why the function behaves that way but the output you see makes it quite clear that your function returns null.

like image 163
David Heffernan Avatar answered Jul 07 '26 08:07

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!