我通过python/c API,让Python调用C语言,出现了如下错误:
ImportError: DLL load failed: %1 不是有效的 Win32 应用程序。
操作步骤:
1.编写C文件 addList.c:
//Python.h has all the required function definitions to manipulate the Python objects #include <Python.h> //This is the function that is called from your python code static PyObject* addList_add(PyObject* self, PyObject* args){ PyObject * listObj; //The input arguments come as a tuple, we parse the args to get the various variables //In this case it's only one list variable, which will now be referenced by listObj if (! PyArg_ParseTuple( args, "O", &listObj )) return NULL; //length of the list long length = PyList_Size(listObj); //iterate over all the elements int i, sum =0; for (i = 0; i < length; i++) { //get an element out of the list - the element is also a python objects PyObject* temp = PyList_GetItem(listObj, i); //we know that object represents an integer - so convert it into C long long elem = PyInt_AsLong(temp); sum += elem; } //value returned back to python code - another python object //build value here converts the C long to a python integer return Py_BuildValue("i", sum); } //This is the docstring that corresponds to our 'add' function. static char addList_docs[] = "add( ): add all elements of the list\n"; /* This table contains the relavent info mapping - <function-name in python module>, <actual-function>, <type-of-args the function expects>, <docstring associated with the function> */ static PyMethodDef addList_funcs[] = { {"add", (PyCFunction)addList_add, METH_VARARGS, addList_docs}, {NULL, NULL, 0, NULL} }; /* addList is the module name, and this is the initialization block of the module. <desired module name>, <the-info-table>, <module's-docstring> */ PyMODINIT_FUNC initaddList(void){ Py_InitModule3("addList", addList_funcs, "Add all ze lists"); }
2.编写run.py
#Though it looks like an ordinary python import, the addList module is implemented in C import addList l = [1,2,3,4,5] print("Sum of List - " + str(l) + " = " + str(addList.add(l)))
3.编写setup.py
#build the modules from distutils.core import setup, Extension setup(name='addList', version='1.0', \ ext_modules=[Extension('addList', ['addList.c'])])
4.cmd运行python setup.py build和python setup.py install,生成了如下文件:
最后运行run.py,出现如下错误:
不知道哪里错了,之前用CTypes也出现了这样的错误
初接触python,对python的环境很懵逼