Python在各个方面的开发都有涉及,但也不是所有需求都能满足,例如对于 安全性、性能等要求比较高的场景下就不适用了。
但可以通过C语言写Python扩展的方式,来扩展现有的Python功能,现在将以前写Python扩展的步骤记录下来以免忘记
#include "Python.h"
/*
定义一个包装函数 实现执行shell命令的功能
*/
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 PyLong_FromLong(sts);
}
/*
定义导出到Python中的方法列表
*/
static PyMethodDef spamMethods[] =
{
{ "system",spam_system, METH_VARARGS, "system(cmd)" },
{ NULL, NULL, 0, NULL }
};
/*
定义导出到Python的模块
*/
static struct PyModuleDef spammodule = {
PyModuleDef_HEAD_INIT,
"spam", /* name of module */
"test python C", /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
spamMethods
};
PyMODINIT_FUNC PyInit_spam(void)
{
return PyModule_Create(&spammodule);
}
windows下我用的vs IDE,其它IDE配置项是一样的,区别只在于位置不同而已。
指定编译 连接的 Python头文件、库文件路径
指定 Python静态库路径
编译后得到dll文件,将dll文件重命名扩展名为*.pyd,放到Python的库目录 site-packages下,运行Python解释器
import 模块名调用即可