你想在C中安全的执行某个Python调用并返回结果给C。 例如,你想在C语言中使用某个Python函数作为一个回调。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
PyObject *pyfunc(PyObject *self, PyObject *args) { ... Py_BEGIN_ALLOW_THREADS // Threaded C code. Must not use Python API functions ... Py_END_ALLOW_THREADS ... return result; }
1. 在C语言中调用Python非常简单,不过设计到一些小窍门。 下面的C代码告诉你怎样安全的调用:
#include <Python.h>
/* Execute func(x,y) in the Python interpreter.  The
   arguments and return result of the function must
   be Python floats */
double call_func(PyObject *func, double x, double y) {
  PyObject *args;
  PyObject *kwargs;
  PyObject *result = 0;
  double retval;
  /* Make sure we own the GIL */
  PyGILState_STATE state = PyGILState_Ensure();
  /* Verify that func is a proper callable */
  if (!PyCallable_Check(func)) {
    fprintf(stderr,"call_func: expected a callable\n");
    goto fail;
  }
  /* Build arguments */
  args = Py_BuildValue("(dd)", x, y);
  kwargs = NULL;
  /* Call the function */
  result = PyObject_Call(func, args, kwargs);
  Py_DECREF(args);
  Py_XDECREF(kwargs);
  /* Check for Python exceptions (if any) */
  if (PyErr_Occurred()) {
    PyErr_Print();
    goto fail;
  }
  /* Verify the result is a float object */
  if (!PyFloat_Check(result)) {
    fprintf(stderr,"call_func: callable didn't return a float\n");
    goto fail;
  }
  /* Create the return value */
  retval = PyFloat_AsDouble(result);
  Py_DECREF(result);
  /* Restore previous GIL state and return */
  PyGILState_Release(state);
  return retval;
fail:
  Py_XDECREF(result);
  PyGILState_Release(state);
  abort();   // Change to something more appropriate
}
要使用这个函数,你需要获取传递过来的某个已存在Python调用的引用。 有很多种方法可以让你这样做, 比如将一个可调用对象传给一个扩展模块或直接写C代码从已存在模块中提取出来。
下面是一个简单例子用来掩饰从一个嵌入的Python解释器中调用一个函数:
#include <Python.h>
/* Definition of call_func() same as above */
...
/* Load a symbol from a module */
PyObject *import_name(const char *modname, const char *symbol) {
  PyObject *u_name, *module;
  u_name = PyUnicode_FromString(modname);
  module = PyImport_Import(u_name);
  Py_DECREF(u_name);
  return PyObject_GetAttrString(module, symbol);
}
/* Simple embedding example */
int main() {
  PyObject *pow_func;
  double x;
  Py_Initialize();
  /* Get a reference to the math.pow function */
  pow_func = import_name("math","pow");
  /* Call it using our call_func() code */
  for (x = 0.0; x < 10.0; x += 0.1) {
    printf("%0.2f %0.2f\n", x, call_func(pow_func,x,2.0));
  }
  /* Done */
  Py_DECREF(pow_func);
  Py_Finalize();
  return 0;
}
要构建例子代码,你需要编译C并将它链接到Python解释器。 下面的Makefile可以教你怎样做(不过在你机器上面需要一些配置)。
all::
        cc -g embed.c -I/usr/local/include/python3.3m \
          -L/usr/local/lib/python3.3/config-3.3m -lpython3.3m
编译并运行会产生类似下面的输出:
0.00 0.00
0.10 0.01
0.20 0.04
0.30 0.09
0.40 0.16
...
下面是一个稍微不同的例子,展示了一个扩展函数, 它接受一个可调用对象和其他参数,并将它们传递给 call_func() 来做测试:
/* Extension function for testing the C-Python callback */
PyObject *py_call_func(PyObject *self, PyObject *args) {
  PyObject *func;
  double x, y, result;
  if (!PyArg_ParseTuple(args,"Odd", &func,&x,&y)) {
    return NULL;
  }
  result = call_func(func, x, y);
  return Py_BuildValue("d", result);
}
使用这个扩展函数,你要像下面这样测试它:
>>> import sample
>>> def add(x,y):
...     return x+y
...
>>> sample.call_func(add,3,4)
7.0
>>>