Nested Python C Extensions/Modules?

风格不统一 提交于 2019-12-21 04:53:14

问题


How do I compile a C-Python module such that it is local to another? E.g. if I have a module named "bar" and another module named "mymodule", how do I compile "bar" so that it imported via "import mymodule.bar"?

(Sorry if this is poorly phrased, I wasn't sure what the proper term for it was.)

I tried the following in setup.py, but it doesn't seem to work:

from distutils.core import setup, Extension

setup(name='mymodule',
      version='1.0',
      author='Me',
      ext_modules=[Extension('mymodule', ['mymodule-module.c']),
                   Extension('bar', ['bar-module.c'])])

Edit

Thanks Alex. So this is what I ended up using:

from distutils.core import setup, Extension

PACKAGE_NAME = 'mymodule'

setup(name=PACKAGE_NAME,
      version='1.0',
      author='Me',
      packages=[PACKAGE_NAME],
      ext_package=PACKAGE_NAME
      ext_modules=[Extension('foo', ['mymodule-foo-module.c']),
                   Extension('bar', ['mymodule-bar-module.c'])])

with of course a folder named "mymodule" containing __init__.py.


回答1:


The instructions are here:

Extension('foo', ['src/foo1.c', 'src/foo2.c'])

describes an extension that lives in the root package, while

Extension('pkg.foo', ['src/foo1.c', 'src/foo2.c'])

describes the same extension in the pkg package. The source files and resulting object code are identical in both cases; the only difference is where in the filesystem (and therefore where in Python’s namespace hierarchy) the resulting extension lives.

Remember, a package is always a directory (or zipfile) containing a module __init__. To create a module that's a package body, that module will be called __init__ and live under the package's directory (or zipfile). I've never done that in C; if it doesn't work to do it directly, name the module e.g. _init instead, and in __init__.py do from _init import * (one of the very few legitimate uses of from ... import *;-).



来源:https://stackoverflow.com/questions/1681281/nested-python-c-extensions-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!