问题描述
所以我差不多完成了。现在我有工作代码调用python回调函数。
So I'm almost done. Now I have working code which calls python callback function.
现在我只需要的是如何传递参数到python回调函数。
Only thing I need now is how to pass argument to the python callback function.
我的callback.c是:
My callback.c is:
#include <stdio.h>
typedef void (*CALLBACK)(void);
CALLBACK my_callback = 0;
void set_callback(CALLBACK c);
void test(void);
void set_callback(CALLBACK c) {
my_callback = c;
}
void test(void) {
printf("Testing the callback function\n");
if (my_callback) (*my_callback)();
else printf("No callback registered\n");
}
我的callback.i是:
My callback.i is:
// An entirely different mechanism for handling a callback
%module callback
%{
typedef void (*CALLBACK)(void);
extern CALLBACK my_callback;
extern void set_callback(CALLBACK c);
extern void my_set_callback(PyObject *PyFunc);
extern void test(void);
%}
extern CALLBACK my_callback;
extern void set_callback(CALLBACK c);
extern void my_set_callback(PyObject *PyFunc);
extern void test(void);
%{
static PyObject *my_pycallback = NULL;
static void PythonCallBack(void)
{
PyObject *func, *arglist;
PyObject *result;
func = my_pycallback; /* This is the function .... */
arglist = Py_BuildValue("()"); /* No arguments needed */
result = PyEval_CallObject(func, arglist);
Py_DECREF(arglist);
Py_XDECREF(result);
return /*void*/;
}
void my_set_callback(PyObject *PyFunc)
{
Py_XDECREF(my_pycallback); /* Dispose of previous callback */
Py_XINCREF(PyFunc); /* Add a reference to new callback */
my_pycallback = PyFunc; /* Remember new callback */
set_callback(PythonCallBack);
}
%}
%typemap(python, in) PyObject *PyFunc {
if (!PyCallable_Check($input)) {
PyErr_SetString(PyExc_TypeError, "Need a callable object!");
return NULL;
}
$1 = $input;
}
我应该怎么做,所以我可以传递参数 my_callback
?
任何帮助将非常感谢。
It works well. What should I do so I can pass argument to my_callback
?Any help will be greatly appreciated!
推荐答案
回调的参数是<$ c $的第二个参数c> PyEval_CallObject()。现在你正在构建一个空的元组,这意味着没有参数。所以,改变。您现在的位置:
The arguments to the callback are the second argument to PyEval_CallObject()
. Right now you're building an empty tuple, which means "no arguments". So, change that. Where you now do:
arglist = Py_BuildValue("()"); /* No arguments needed */
您可以通过 Py_BuildValue
无论你希望Python函数接收什么参数。例如,如果你想传递一个整数,一个字符串和一个从某处获得的Python对象,你可以这样做:
you instead pass Py_BuildValue
whatever arguments you want the Python function to receive. For example, if you want to pass the callback an integer, a string and a Python object you got from somewhere, you would do:
arglist = Py_BuildValue("(isO)", the_int, the_str, the_pyobject);
这篇关于SWIG将参数传递给python回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!