如何构建Python C扩展,以便可以从模块导入它 [英] How to build a Python C Extension so I can import it from a module

查看:254
本文介绍了如何构建Python C扩展,以便可以从模块导入它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python项目,其中包含许多与distutils打包在一起的子模块.我想在C中构建一些Python扩展以生活在其中一些子模块中,但我不明白如何使Python扩展生活在子模块中.以下是我正在寻找的最简单的示例:

I have a Python project with many sub-modules that I package up with distutils. I would like to build some Python extensions in C to live in some of these sub-modules but I don't understand how to get the Python extension to live in a submodule. What follows is the simplest example of what I'm looking for:

这是我的Python扩展名c_extension.c:

Here is my Python extension c_extension.c:

#include <Python.h>

static PyObject *
get_answer(PyObject *self, PyObject *args)
{
    return Py_BuildValue("i", 42);
}

static PyMethodDef Methods[] = {
    {"get_answer",  get_answer, METH_VARARGS, "The meaning of life."},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
initc_extension(void) {
  (void) Py_InitModule("c_extension", Methods);
}

这是一个有效的setup.py:

from distutils.core import setup
from distutils.extension import Extension

setup(name='c_extension_demo',
      ext_modules = [Extension('c_extension', sources = ['c_extension.c'])])

在virtualenv中安装后,我可以这样做:

After installing in an virtualenv I can do this:

>>> import c_extension
>>> c_extension.get_answer()
42

但是我想让c_extension生活在一个子模块中,例如foo.bar.我需要在此管道中进行哪些更改才能使Python外壳中的行为如下所示:

But I would like to have c_extension live in a sub-module, say foo.bar. What do I need to change in this pipeline to be able to get the behavior in the Python shell to be like this:

>>> import foo.bar.c_extension
>>> foo.bar.c_extension.get_answer()
42

推荐答案

只需更改

Extension('c_extension', ...)

Extension('foo.bar.c_extension', ...)

与往常一样,每个foobar目录中都将需要__init__.py文件.要将这些文件与setup.py中的模块打包在一起,您需要添加

You will need __init__.py files in each of the foo and bar directories, as usual. To have these packaged with the module in your setup.py, you need to add

packages = ['foo', 'foo.bar'],

到您的setup()调用,您将需要目录结构

to your setup() call, and you will need the directory structure

setup.py
foo/
    __init__.py
    bar/
        __init__.py

在您的源目录中.

这篇关于如何构建Python C扩展,以便可以从模块导入它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆