C扩展库中回调Python函数

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

// 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"