python如何调用C, 如何注册成C的回调函数(python后台程序常用方法)
来源:互联网 发布:h3c s5000 端口聚合 编辑:程序博客网 时间:2024/05/19 05:02
其实是python后台程序常用方法:
C开发完成底层的功能,python直接把C当做python模块进行调用。
需要做两个工作:
- python能调用C语言的函数;
- python通过调用C函数,并注册python的回调函数,C代码通过python回调函数告诉Python当前实时进度和状态;
1,python如何调用C语言
主要就是应用ctypes这个模块,too simple too naive。
python代码是这样滴:
C代码是这样滴:
就像C语言编译出来的.so库只是python的一个模块,直接调用就可以了。
2,python注册C语言的回调函数
其实也不难,python的函数本身也是python的对象,实现也就简单了:python的回调函数:
python 两个回调函数:OnPyVideoAnalyzeResultCallback和OnPyVideoStateCallback。如何把这两个python函数注册成C代码的回调函数呢?
python部分是这样注册滴:
应用这个来设置:CFUNCTYPE第一个参数是python回调函数的返回值,如果没有就是None。
第二个及其以后的就是python回调函数的参数类型了。
CMPRESULTFUNC = CFUNCTYPE(None, c_ulong, c_ulong, c_ulong, c_ulong)//创建一个c函数类型的对象工厂,该函数返回值为None,有三个入参,都为unsigned long。
CMPRESULTFUNC(OnPyVideoAnalyzeResultCallback)根据Python可调用对象生成函数。
mylib.VideoAnalyzeStart(ulHandle, CMPRESULTFUNC(OnPyVideoAnalyzeResultCallback), CMPSTATEFUNC(OnPyVideoStateCallback))//设置回调函数
C部分是这样的:
C部分不用管。但是如何确定python函数参数与C函数参数的对应关系呢?
python函数参数与C函数参数的对应表(其实也可以叫ctypes类型表):
一个大坑:需要注意CMPRESULTFUNC(OnPyVideoAnalyzeResultCallback)这个指针函数是有自己的生存空间的,如果生存空间已过,会被释放,C代码再回调的时候,就会使用一个过期指针。
这里建议使用一个全局的python指针。
见官网的解释:https://docs.python.org/3/library/ctypes.html#ctypes.c_longNote
Make sure you keep references to CFUNCTYPE()
objects as long as they are used from C code. ctypes
doesn’t, and if you don’t, they may be garbage collected, crashing your program when a callback is made.
Also, note that if the callback function is called in a thread created outside of Python’s control (e.g. by the foreign code that calls the callback), ctypes creates a new dummy Python thread on every invocation. This behavior is correct for most purposes, but it means that values stored with threading.local
will not survive across different callbacks, even when those calls are made from the same C thread.
- python如何调用C, 如何注册成C的回调函数(python后台程序常用方法)
- python如何调用C, 如何注册成C的回调函数(python后台程序常用方法)
- C/C++中如何调用Python方法
- python如何调用c语言
- C调用python,如何调用pymongo模块
- 转帖:C/C++中如何调用Python方法
- python调用c的方法
- Python如何调用C语言接口
- C/C++中如何调用Python
- 在python中将回调函数传给c动态库
- python的回调函数
- C# 调用C/C++回调函数
- c++调用c时回调函数的处理
- jna调用c 的dll(包含回调函数)
- Python调用C语言之如何调用动态链接库
- python 回调函数和回调方法的实现
- python 回调函数和回调方法的实现
- python调用C模块的方法
- 第十四周项目一-哈希表及其运算的实现
- STL学习之set与multiset操作练习
- linux查看时间
- PopupWindow标题栏不能遮罩的解决办法
- CentOS安装Eclipse 和As
- python如何调用C, 如何注册成C的回调函数(python后台程序常用方法)
- Learn How to Use Neo4J with Node.js
- 8、新手入手树莓派教程--csi摄像头的安装
- mysql的基础知识
- CRC 循环冗余校验码 的计算方法
- ZYNQ跑系统 系列(二) petalinux方式移植linux
- VS2015工程部署问题解决
- 09-CSS定位补充 z-index,精灵图
- Ubuntu下配置SVN自动发送邮件通知