0
votes

I have a shared lib libtest.so made from test.c:

#include <stdio.h>
int value;
void fn() { printf("%d\n", value); }

Now I'm wrapping this library from Python using CTypes. I know that I can read value from Python as follows:

In[2]: c_int.in_dll(lib, "value")
Out[2]: c_int(0)

(I learnt the above from Mapping a global variable from a shared library with ctypes.)

However, if I try to write to the same, then it complains:

In[3]: c_int.in_dll(lib, "value") = 2
  File "<ipython-input-4-5a1e8ea6a1b4>", line 1
    c_int.in_dll(lib, "value") = 2
                                  ^
SyntaxError: can't assign to function call

Presumably this is because the c_int object doesn't directly "point" to the C memory location.

Of course, I can write and export a setValue function that can receive data from Python to modify value from within C, but I am wondering whether there is any way to do without that.

Assigning Python function to ctypes pointer variable seems to indicate this is not possible, but would like a specific answer hence posting the specific question.

1

1 Answers

1
votes

Your c_int does point at the value of test.c. You will want to write to the valueattribute of the c_int to write to the underlying memory that the c_int wraps. Otherwise you would simply be replacing one Python object with another in Python-land and not having any effect in C land. For example:

>>> import ctypes
>>> i = ctypes.c_int()
>>> i
c_int(0)
>>> i.value = 10
>>> i
c_int(10)