0

I'm trying to use CMake to build a fortran extension following this SO post in a setup.py.

When I run pip install . -v, I can see that my extension builds just fine, but then the binary (the .so file) is not installed alongside the python scripts which will try to import it. How can I guarantee that my extension is installed?

Here is my setup.py for reference

import os
import pathlib
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as build_ext_orig

class CMakeExtension(Extension):
    def __init__(self, name):
        # don't invoke the original build_ext for this special extension
        super().__init__(name, sources=[])


class build_ext(build_ext_orig):
    def run(self):
        for ext in self.extensions:
            self.build_cmake(ext)
        super().run()

    def build_cmake(self, ext):
        cwd = pathlib.Path().absolute()

        # these dirs will be created in build_py, so if you don't have
        # any python sources to bundle, the dirs will be missing
        build_temp = pathlib.Path(self.build_temp)
        build_temp.mkdir(parents=True, exist_ok=True)
        extdir = pathlib.Path(self.get_ext_fullpath(ext.name))
        extdir.mkdir(parents=True, exist_ok=True)
        
        # example of cmake args
        config = 'Debug' if self.debug else 'Release'
        cmake_args = [
            '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY='+str(extdir.parent.absolute()),
            '-DCMAKE_BUILD_TYPE=' + config,
            '-DBUILD_PYTHON_MODULE=ON',
            '-DBUILD_FORTRAN_LIBRARY=OFf',
            '-DBUILD_THE_EXAMPLES=OFF',
        ]
        
        # example of build args
        build_args = [
            '--config', config, 
        ]
        
        os.chdir(str(build_temp))
        self.spawn(['cmake', str(cwd)] + cmake_args)
        if not self.dry_run:
            self.spawn(['cmake', '--build', '.'] + build_args)
        # Troubleshooting: if fail on line above then delete all possible 
        # temporary CMake files including "CMakeCache.txt" in top level dir.
        os.chdir(str(cwd))


setup(name = 'mypythonlibrary',
      packages=['mypythonlibrary'],
      version='0.1',
      ext_modules=[CMakeExtension('mypythonlibrary/myfortranlibrary')],
      cmdclass={'build_ext': build_ext,})
nicholaswogan
  • 631
  • 6
  • 13
  • 1
    Consider using [scikit-build](https://scikit-build.readthedocs.io/en/latest/usage.html) instead of a hand-rolled solution. It uses CMake natively. – Alex Reinking Jul 27 '21 at 16:06

1 Answers1

0

Its best to just you skbuild. They have examples for c++, cython, c. I just put together some examples for f2py/fortran: https://github.com/Nicholaswogan/skbuild-f2py-examples

nicholaswogan
  • 631
  • 6
  • 13