C语言调用Python模块(Ubuntu Linux)
关键词:python 调用c语言 c语言调用python脚本 c语言调用python函数
Ubuntu下首先要配置下环境;sudo apt-get install python-dev
以下是一个简单的例子:
#include “/usr/include/python2.5/Python.h”
#include <stdio.h>
int main(int arg,char **argv){
PyObject *modelname,*model,*dict,*func,*args;
char *name=”os”;//模块名
//初始化Python
Py_Initialize();
if (!Py_IsInitialized()){
printf(“初始化失败n”);
return -1;
}
//直接运行Python语句
PyRun_SimpleString(“print ‘初始化成功'”);
//导入Python模块
modelname=PyString_FromString(name);
model=PyImport_Import(modelname);
if (model){
printf(“Load model okn”);
}
else{
printf(“Model %s not found!n”,name);
return -1;
}
dict=PyModule_GetDict(model);
if(!dict){
printf(“获取字典失败n”);
return -1;
}
else{
printf(“获取字典成功n”);
}
//从模块中找到“System”函数
func=PyDict_GetItemString(dict,”system”);
if(!func || !PyCallable_Check(func)){
printf(“函数无效n”);
return -1;
}
args=PyTuple_New(1);
PyTuple_SetItem(args,0,Py_BuildValue(“s”,”ls”));//l=long,s=string…
//调用函数
PyObject_CallObject(func,args);
Py_DECREF(modelname);
Py_DECREF(model);
Py_DECREF(func);
Py_DECREF(args);
Py_DECREF(dict);
//垃圾回收
Py_Finalize();
return 0;
}
下面就是编译连接生成可执行文件。
下面是用Python写的编译脚本。
#!/usr/bin/env python
import os
import sys
f=raw_input(“C/C++ File:”);
out=raw_input(“Output file:”);
sys.stdout.write(“Trying to Complie C File using gcc…n”);
sys.stdout.write(“———————————————————n”);
if out==” or out==None:
os.system(“gcc “+f +” -L/usr/lib/python2.5/config -lpython2.5 -lpthread -lm -ldl -lutil”);
else:
os.system(“gcc “+f +” -L/usr/lib/python2.5/config -lpython2.5 -lpthread -lm -ldl -lutil “+”-o “+out);
sys.stdout.write(“———————————————————n”);
sys.stdout.write(“Done!n”);