C扩展库中回调Python函数

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
// 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 脚本
from pyArchive import *
from ctypes import *

# 回调函数必须有一个int型的返回值
def set_callback_fn(abc) :
    print "t_callback_fn say : {0}".format(abc)
    return 11

CMPFUNC = 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"

标签: isp 脚本

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:Android添加触摸手势识别监听

下一篇:数学表达式计算器