根据上面的内容,可编写如下程序:
#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 SpamMethods[] = {
{
"system", spam_system, METH_VARARGS,"Execute a shell command."},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
initspam(void)
{
Py_InitModule("spam", SpamMethods);
}
利用codeblocks新建工程,编译dll, 具体操作步骤可参考Python之美[从菜鸟到高手]。通过这篇文章,我成功在python里调用到了spam.system(‘ls -s’)。
1 标准异常
阅读python官方文档Extending Python with C\C++后,第二小节是关于异常的,我试着在上面代码中加入异常的语句,如下:
#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);
if (sts > 0) //添加异常,如果系统没有传入的命令,返回值不为0
{
//这里的异常PyExc_ArithmeticError是我随便选的预定义异常对象
PyErr_SetString(PyExc_ArithmeticError, "something is wrong");
return NULL;
}
return Py_BuildValue("i", sts);
}
static PyMethodDef SpamMethods[] = {
{
"system", spam_system, METH_VARARGS,"Execute a shell