编写python扩展.
代码:
#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 PyLong_FromLong(sts); } static PyMethodDef SpamMethods[] = { {"system", spam_system, METH_VARARGS, "Execute a shell command."}, {NULL, NULL, 0, NULL} /* Sentinel */ }; static struct PyModuleDef spammodule = { PyModuleDef_HEAD_INIT, "spam", /* name of module */ NULL, /* 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); }
编译选项:
releaee版
dll名字必须为spam.pyd
测试:
>>> import spam
>>> dir(spam)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'system']
>>> spam.system('dir')
驱动器 G 中的卷是 ll6_za
卷的序列号是 C0F5-30DE
G:\temp\ConsoleApplication1\Release 的目录
2018/03/19 00:38 <DIR> .
2018/03/19 00:38 <DIR> ..
2018/03/19 00:36 746 ConsoleApplication1.exp
2018/03/19 00:36 27,307 ConsoleApplication1.iobj
2018/03/19 00:36 33,648 ConsoleApplication1.ipdb
2018/03/19 00:36 1,942 ConsoleApplication1.lib
2018/03/19 00:36 512,000 ConsoleApplication1.pdb
- 上一篇 Update 20180317.
- 下一篇 Update.