2

So in python native extension, is it possible to implement multiple modules in a single shared library? Then what would be the name of the shared library should be?

PyMODINIT_FUNC PyInit_foo(void) { PyModule_Create(...); }
PyMODINIT_FUNC PyInit_bar(void) { PyModule_Create(...); }

Should I name the library file foo.so or bar.so? and will import foo; import just foo or both foo and bar modules?

fluter
  • 13,238
  • 8
  • 62
  • 100
  • 1
    [Here's a relevant question that does](https://stackoverflow.com/questions/30157363/collapse-multiple-submodules-to-one-cython-extension) what you want (but using Cython). You should be able to use substantially the same approach here. – DavidW Sep 14 '20 at 07:13

1 Answers1

2

Yes you can. The easiest way is to create hardlinks named after each module for importlib to be able to find the module. The statement import <x> imports the module named <x> by looking for an exported PyInit_<x> function from <x>-*.so.

So say, you build as foo.so and create bar.so as a hardlink to foo.so. Your package structure would look like:

/mypackage/__init__.py
/mypackage/foo.so
/mypackage/bar.so -> foo.so # hardlink
MEE
  • 2,114
  • 17
  • 21
  • Does setuptools support auto creation of the hardlink? – fluter Jul 23 '23 at 13:30
  • With setuptools, you can add two extensions with different names, e.g.,: `setup(ext_modules=[Extension(name="mypackage.foo", sources=["src/.../foo.cpp"], ...), Extension(name="mypackage.bar", sources=["src/.../foo.cpp"], ...)], ...` – MEE Jul 24 '23 at 22:29