问题
你想在C中安全的执行某个Python调用并返回结果给C。 例如,你想在C语言中使用某个Python函数作为一个回调。
解决方案
在C语言中调用Python非常简单,不过涉及到一些小窍门。 下面的C代码告诉你怎样安全的调用:
#include
/* Execute func(x,y) in the Python interpreter. The
arguments and return result of the function must be Python floats */
do
本文实例讲述了Python调用C语言的方法。分享给大家供大家参考,具体如下:
Python中的ctypes模块可能是Python调用C方法中最简单的一种。ctypes模块提供了和C语言兼容的数据类型和函数来加载dll文件,因此在调用时不需对源文件做任何的修改。也正是如此奠定了这种方法的简单性。
示例如下
实现两数求和的C代码,保存为add.c
//sample C file to add 2 numbers - int and floats
#include
int add_int(int,
Python中的ctypes模块可能是Python调用C方法中最简单的一种。ctypes模块提供了和C语言兼容的数据类型和函数来加载dll文件,因此在调用时不需对源文件做任何的修改。也正是如此奠定了这种方法的简单性。
示例如下
实现两数求和的C代码,保存为add.c
//sample C file to add 2 numbers - int and floats
#include
int add_int(int, int);
float add_float(float, float);
i