编译python C扩展名

问题描述 投票:0回答:1

我为CPython扩展编写了以下代码:

#include <Python.h>
static PyObject *greeting(PyObject* self)
{
        return Py_BuildValue("s" , "Hello python modules!!!");
}

static char *my_docstring = "This is a sample docstring";

static PyMethodDef greeting_funcs[] = {
    {"greeting" , (PyCFunction)greeting , METH_NOARGS , my_docstring} , {NULL}
};

void initModule(void){
    Py_InitModule3("greeting" , greeting_funcs , "Module example!!!");
}

并且当我在IPython3 shell中执行以下命令时

from setuptools import setup , Extension
modules = [Extension('mod', sources=["/home/spm/python_module/mod.c"])] 
setup(ext_modules=modules) 

我收到错误:

SystemExit: usage: ipython3 [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts]
or: ipython3 --help [cmd1 cmd2 ...]
or: ipython3 --help-commands
or: ipython3 cmd --help

error: no commands supplied

感谢您的帮助。谢谢。

python c setuptools python-extensions
1个回答
0
投票

首先,您的mod.c无法编译。 Py_InitModule3已在Python 3中删除;您必须创建一个PyModuleDef结构并添加一个名为PyModuleDef的初始化函数,该函数会传递PyInit_{library name}引用到PyModuleDef初始化模块:

PyModule_Create

当我在IPython3 shell中执行以下命令时,出现错误

通常不从IPython调用此代码。将其放入名为PyModule_Create的脚本中,然后从终端执行,提供#include <Python.h> #define MY_DOCSTRING "This is a sample docstring" static PyObject *greeting(PyObject* self) { return Py_BuildValue("s" , "Hello python modules!!!"); } static PyMethodDef greeting_funcs[] = { {"greeting" , (PyCFunction)greeting , METH_NOARGS , MY_DOCSTRING} , {NULL} }; // python module definition static struct PyModuleDef greetingModule = { PyModuleDef_HEAD_INIT, "greeting", "Module example!!!", -1, greeting_funcs }; // register module namespace PyMODINIT_FUNC PyInit_mod(void) { PyObject *module; module = PyModule_Create(&greetingModule); if (module == NULL) return NULL; return module; } 函数应调用的任务,例如

setup.py

构建扩展模块并将其放入当前目录。

当然,您也可以在IPython中对此进行模仿:

setup

但是,更好的解决方案是将设置代码写入$ python setup.py build_ext --inplace 脚本。然后,您可以通过In [1]: import sys In [2]: sys.argv.extend(["build_ext", "--inplace"]) In [3]: from setuptools import setup, Extension In [4]: modules = [Extension('mod', sources=["mod.c"])] In [5]: setup(ext_modules=modules) running build_ext ... In [6]: sys.argv = sys.argv[:1] 魔术在IPython中执行它:

setup.py
© www.soinside.com 2019 - 2024. All rights reserved.