I know that if I have a global variable (let’s say a double called N) I can read it using:
JavaScript
x
4
1
from ctypes import c_double, CDLL
2
c_lib = CDLL('path/to/library.so')
3
N = c_double.in_dll(c_lib, "N").value
4
but what if my variable is a pointer? How can I read the contents of the pointer in to a python list?
To be clearer, N is declared in the following way in the shared library:
JavaScript
1
2
1
double N = 420.69;
2
Advertisement
Answer
Given this (Windows) DLL source:
JavaScript
1
7
1
int ints[10] = {1,2,3,4,5,6,7,8,9,10};
2
double doubles[5] = {1.5,2.5,3.5,4.5,5.5};
3
4
__declspec(dllexport) char* cp = "hello, world!";
5
__declspec(dllexport) int* ip = ints;
6
__declspec(dllexport) double* dp = doubles;
7
You can access these exported global variables with:
JavaScript
1
21
21
1
>>> from ctypes import *
2
>>> dll = CDLL('./test')
3
>>> c_char_p.in_dll(dll,'cp').value
4
b'hello, world!'
5
>>> POINTER(c_int).in_dll(dll,'ip').contents
6
c_long(1)
7
>>> POINTER(c_int).in_dll(dll,'ip')[0]
8
1
9
>>> POINTER(c_int).in_dll(dll,'ip')[1]
10
2
11
>>> POINTER(c_int).in_dll(dll,'ip')[9]
12
10
13
>>> POINTER(c_int).in_dll(dll,'ip')[10] # Undefined behavior, past end of data.
14
0
15
>>> POINTER(c_double).in_dll(dll,'dp')[0]
16
1.5
17
>>> POINTER(c_double).in_dll(dll,'dp')[4]
18
5.5
19
>>> POINTER(c_double).in_dll(dll,'dp')[5] # Also UB, past end of data.
20
6.9532144253691e-310
21
To get a list, if you know the size:
JavaScript
1
3
1
>>> list(POINTER(c_int * 10).in_dll(dll,'ip').contents)
2
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
3