简体   繁体   English

SWIG将参数传递给python回调函数

[英]SWIG passing argument to python callback function

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. 我现在唯一需要的是如何将参数传递给python回调函数。

My callback.c is: 我的callback.c是:

#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");
}

My callback.i is: 我的callback.i是:

// 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;
}

It works well. 它运作良好。 What should I do so I can pass argument to my_callback ? 我应该怎么做才能将参数传递给my_callback Any help will be greatly appreciated! 任何帮助将不胜感激!

The arguments to the callback are the second argument to PyEval_CallObject() . 回调的参数是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 */

you instead pass Py_BuildValue whatever arguments you want the Python function to receive. 你改为传递Py_BuildValue你希望Python函数接收的参数。 For example, if you want to pass the callback an integer, a string and a Python object you got from somewhere, you would do: 例如,如果要将回调传递给整数,字符串和从某处获得的Python对象,您可以:

arglist = Py_BuildValue("(isO)", the_int, the_str, the_pyobject);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM