我正在学习如何制作可在Python中使用的C扩展。
我遵循了一个教程(基本上,复制粘贴,但不是盲目,试用)。代码是
#include <Python.h>
static PyObject *exmodError;
static PyObject* exmod_say_hello(PyObject* self, PyObject *args){
const char* msg;
int sts = 0;
if(!PyArg_ParseTuple(args, "s", &msg)){
return NULL;
}
if(strcmp("this_is_error_msg", msg) == 0){
PyErr_SetString(exmodError, "Well, an error occured.");
return NULL;
}else{
printf("In C world\nYour message is : %s\n", msg);
sts = 21;
}
return Py_BuildValue("i", sts);
}
static PyObject* exmod_add(PyObject* self, PyObject *args){
double a, b;
double sts = 0;
return NULL;
if(!PyArg_ParseTuple(args, "dd", &a, &b)){
return NULL;
}
sts = a + b;
printf("This is C world, addition of %f + %f is %f", a, b, sts);
return Py_BuildValue("d", sts);
}
static PyMethodDef exmod_methods[] = {
// "PythonName", "C-FunctionName", "ArgumentPresentation",
// "Description"
{"say_hello", exmod_say_hello, METH_VARARGS, "Say Hello from C and print message."},
{"add", exmod_add, METH_VARARGS, "Add two numbers in C."},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC initexmod(void){
PyObject *m;
m = Py_InitModule("exmod", exmod_methods);
if(m == NULL){
return;
}
exmodError = PyErr_NewException("exMod.err", NULL, NULL);
Py_INCREF(exmodError);
pyModule_AddObject(m, "error", exmodError);
}
上面,文件具有虚拟功能,可以做无意识的事情。
然后,setup.py文件是
__author__ = 'some.author'
from distutils.core import setup, Extension
module1 = Extension('exmod',
include_dirs=["/usr/local/include", "/usr/include/python2.7"],
sources=["exmodmodule.c"]
)
setup(
name="exmod",
version="1.0.0",
description="This is a tutorial Package",
author="someOne",
url="www.9gag.com",
ext_module=[module1]
)
我已成功构建并安装它。但是当我在python解释器中导入并运行exmod.add时,会发生错误。
>>> exmod.add(5.0, 6.7)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
SystemError: error return without exception set
请帮助我弄清楚'我做错了什么',因为我是制作C-extension的新手。
答案 0 :(得分:0)
查看函数exmod_add
的第3行。在那里,您返回NULL
,表示发生了异常。但是,由于您没有引发异常,因此您将获得SystemError: error return without exception set
。
static PyObject* exmod_add(PyObject* self, PyObject *args){
double a, b;
double sts = 0;
return NULL; /***** this one *****/
if(!PyArg_ParseTuple(args, "dd", &a, &b)){
return NULL;
}
sts = a + b;
printf("This is C world, addition of %f + %f is %f", a, b, sts);
return Py_BuildValue("d", sts);
}