C扩展库中回调Python函数,扩展回调python函数,[C/C++]代码//
C扩展库中回调Python函数,扩展回调python函数,[C/C++]代码//
[C/C++]代码
// c 程序 段static PyObject *gc_before_extract = NULL;/// 设置回调static PyObject *SetBeforeCallbackFn(PyObject *dummy, PyObject *args){PyObject *temp = NULL;if (PyArg_ParseTuple(args, "O:set_callback", &temp)) { if (!PyCallable_Check(temp)) { PyErr_SetString(PyExc_TypeError, "parameter must be callable"); } Py_XINCREF(temp); /* Add a reference to new callback */ Py_XDECREF(gc_before_extract); /* Dispose of previous callback */ gc_before_extract = temp; /* Remember new callback */}return Py_BuildValue("l", (gc_before_extract == NULL) ? 0 : 1);}/// 调用上面函数设置的python脚本函数int BeforeExt(char *pBeforeExtract){PyObject* pArgs = NULL;PyObject* pRetVal = NULL;int nRetVal = 0;pArgs = Py_BuildValue("(s)", pFileName);pRetVal = PyEval_CallObject(gc_before_extract, pArgs);if (pRetVal){ fprintf(stderr, "PyEval_CallObject : ok \r\n"); nRetVal = PyInt_AsLong(pRetVal); fprintf(stderr, "PyEval_CallObject : return : %d \r\n", nRetVal);}Py_DECREF(pArgs);Py_DECREF(pRetVal);return nRetVal;}/// 测试函数static PyObject* my_test_callback(PyObject *self, PyObject *args) { PyObject * arglist; PyObject * result = NULL;BeforeExt("good");result = PyEval_CallObject(gc_before_extract, args); if (result){ Py_DECREF(result); }Py_INCREF(Py_None); return Py_None; }
[Python]代码
/////// python 脚本from pyArchive import *from ctypes import *# 回调函数必须有一个int型的返回值def set_callback_fn(abc) : print "t_callback_fn say : {0}".format(abc) return 11CMPFUNC = CFUNCTYPE(c_int, c_char_p) _callback = CMPFUNC(set_callback_fn) if SetBeforeCallbackFn(_callback): print "set call back ok" my_test_callback("script call : good luck") else : print "set call back fail"
相关内容
- python生成格雷码(gray code),pythongray,格雷码(英文:
- Python 处理各种编码的字符串,python编码字符串,Unicode
- 使用decorator检查子类是否实现了父类要求必须实现的方
- python使用rstrip()函数移除行末空白字符,pythonrstrip,pyt
- python从网页中解析网页的字符编码,python字符,[Python]代
- Python使用win32api获取DLL和EXE文件版本号,,[Python]代码i
- python获得随机字符串,python字符串,如下代码生成随机密
- python读写windows注册表,python读写windows,本文封装了_wi
- python使用pickle,json等序列化dict,picklejson,PersistentDi
- Python删除指定目录下的过期文件,,import osimp
评论关闭