栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

用ctypes替换共享库中的函数指针

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用ctypes替换共享库中的函数指针

从中访问全局变量的方法

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
,除了功能参数之外,用作任何功能的功能似乎都没有实现。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/637206.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号