从中访问全局变量的方法
ctypes是使用
in_dll,但是似乎没有公开的方法来更改函数指针。我只能阅读和调用它,所以我认为没有帮助程序功能是不可能的。
以下示例更改了
int全局变量,但是
CFUNCTYPE实例没有
value成员可以对其进行更改。我添加了一个C帮助程序来设置全局值以解决该问题,并添加一个回调的默认值,以在更改它之前验证它是否已正确访问。
test.c:
#include <stdio.h>#define API __declspec(dllexport)typedef void (*CB)();void dllplot() { printf("defaultn");}API CB plot = dllplot;API int x = 5;API int c_main() { printf("x=%d (from C)n",x); plot(); return 0;}API void set_cb(CB cb) { plot = cb;}test.py:
from ctypes import *PLOT = CFUNCTYPE(None)dll = CDLL('./test')dll.c_main.argtypes = ()dll.c_main.restype = c_intdll.set_cb.argtypes = PLOT,dll.set_cb.restype = None@PLOTdef plotxy(): print("plotxy")x = c_int.in_dll(dll,'x')plot = PLOT.in_dll(dll,'plot')print(f'x={x.value} (from Python)')x.value = 7print('calling plot from Python directly:')plot()print('calling c_main():')dll.c_main()dll.set_cb(plotxy)print('calling plot from Python after setting callback:')plot()print('calling plot from C after setting callback:')dll.c_main()输出:
x=5 (from Python)calling plot from Python directly:defaultcalling c_main():x=7 (from C)defaultcalling plot from Python after setting callback:plotxycalling plot from C after setting callback:x=7 (from C)plotxy
请注意,全局指针用于
.contents访问其值,因此我尝试使用a
POINTER(CFUNCTYPE(None))和using,
plot.contents= plotxy但未正确分配全局变量,C崩溃了。
我什至尝试将实际的全局指针添加到函数指针:
API CB plot = dllplot;API CB* pplot = &plot;
然后使用:
PLOT = CFUNCTYPE(None)PPLOT = POINTER(PLOT)plot = PPLOT.in_dll(dll,'pplot')plot.contents = plotxy
这使我可以通过分配函数
.contents,但
c_main仍称为默认绘图值。因此
CFUNCTYPE,除了功能参数之外,用作任何功能的功能似乎都没有实现。



