c语言如何调用python代码_从C语言中调用Python代码-问答-阿里云开发者社区-阿里云...

1. 在C语言中调用Python非常简单,不过设计到一些小窍门。 下面的C代码告诉你怎样安全的调用:

#include

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

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

>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值