您的位置:首页 > 编程语言 > C语言/C++

用C/C++扩展Python(Extending Python with C or C++)

2010-04-02 14:25 387 查看
用c/c++扩展python的方式有很多,比较常见的方式:1)native,2)swig,3)boost_python,这里简单介绍一下python自带的native方式。官方文档:http://docs.python.org/extending/extending.html1.简单示例: 1.1 span_system.cpp//span_system.cpp #include <Python.h>static PyObject *spam_system(PyObject *self, PyObject *args)
{
const char *command;
int sts;

if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
sts = system(command);
return Py_BuildValue("i", sts);
}
static PyMethodDef libmypyext_methods[]
{
{"spam_system", spam_system, METH_VARARGS, "Description"},
{0, 0}
};
PyMODINIT_FUNC initlibgongmingpyext(){Py_InitModule3("libmypyext", libmypyext_methods, "A Python Extension for Test");}
1.2 编译链接成so
g++ -o libmypyext.so -export-dynamic -m64 -shared span_system.cpp
1.3 python调用#span_system.pyimport libmypyextdef spam_system(command):print libmypyext.spam_system()if __name__ == '__main__':    if len(sys.argv) == 2:        spam_system(sys.argv[1])    else:           print '''python span_system.py your_command'''        sys.exit() 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息