[英]Assign to variable exported from shared library via Python CTypes?
I have a shared lib libtest.so
made from test.c
: 我有一个由test.c
制成的共享库libtest.so
:
#include <stdio.h>
int value;
void fn() { printf("%d\n", value); }
Now I'm wrapping this library from Python using CTypes. 现在,我使用CTypes从Python包装此库。 I know that I can read value
from Python as follows: 我知道我可以从Python 读取 value
,如下所示:
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 .) (我从使用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. 大概是因为c_int对象没有直接“指向” C存储器位置。
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. 当然,我可以写和导出setValue
可以从Python中接收数据修改函数value
从C,但我想知道是否有什么办法没有 ,这样做。
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. 将Python函数分配给ctypes指针变量似乎表明这是不可能的,但是想要特定的答案,因此发布特定的问题。
Your c_int
does point at the value
of test.c
. 您的c_int
确实指向test.c
的value
。 You will want to write to the value
attribute of the c_int
to write to the underlying memory that the c_int
wraps. 您将需要写入c_int
的value
属性以写入c_int
包装的基础内存。 Otherwise you would simply be replacing one Python object with another in Python-land and not having any effect in C land. 否则,您将只是在Python区域中用一个Python对象替换另一个Python对象,而在C区域中则没有任何作用。 For example: 例如:
>>> import ctypes
>>> i = ctypes.c_int()
>>> i
c_int(0)
>>> i.value = 10
>>> i
c_int(10)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.