Search code examples
pythoncythonctypes

How to adjust my external custom library import in __init__.py?


So I have a big folder called Geometry and I divided in CPP folder and Cython folder as follows.

- Geometry
 - CPP (Where all the cpp codes are)
 - Cython
  - src folder
   - Geometry Package
    - Point Package
     - __init__.py
     - libcustom.so
    - Circle Package
     - __init__.py
     - libcustom.so
     - __init__.py (Ignore this file)
    - libcustom.so
  - test folder
  - setup.py

In Point.__init__.py and Circle.__init__.py, I have to add the following

import ctypes
import os
libcustom = ctypes.CDLL(os.path.join(os.path.dirname(__file__), "libcustom.so"))

Now as you can see, in order for my libcustom to work on all packages including Point and Circle, I have to add the libcustom.so in both Point and Circle, which doesn't look so good. Now I want to remove all libcustom.so from Point and Circle and only keep the one outside.

- Geometry
     - CPP (Where all the cpp codes are)
     - Cython
      - src folder
       - Geometry Package
        - Point Package
         - __init__.py
        - Circle Package
         - __init__.py
        - libcustom.so
        - __init__.py (Ignore this file)
      - test folder
      - setup.py

How should I change my Point.__init__.py and Circle.__init__.py code so that it will point a reference to the libcustom.so outside?


Solution

  • Try [Python.Docs]: os.path.dirname(path) twice.

    DLL_NAME = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "libcustom.so")
    

    Or you could use (more modern) [Python.Docs]: pathlib - Object-oriented filesystem paths.

    DLL_NAME = str(pathlib.Path(__file__).absolute().parents[1].joinpath("libcustom.so"))
    

    Note: I assume that "libElements.so" in your snippet is a mistake.