I am trying to import a c++ function for use in Python(3.9) on MacOS. My project has the following structure,
.
├── CMakeLists.txt
├── cmake-build-debug
│ ├── CMakeCache.txt
│ ├── CMakeFiles
│ ├── Testing
│ ├── build.ninja
│ ├── cmake_install.cmake
│ └── libDENCLUS.dylib
├── denclus.py
├── library.cpp
└── library.h
with CMakeLists.txt as,
cmake_minimum_required(VERSION 3.22)
project(DENCLUS)
set(CMAKE_CXX_STANDARD 14)
add_library(DENCLUS SHARED library.cpp)
the header file,
#ifndef DENCLUS_LIBRARY_H
#define DENCLUS_LIBRARY_H
extern "C" void hello();
#endif //DENCLUS_LIBRARY_H
the source file,
#include "library.h"
#include <iostream>
void hello() {
std::cout << "Hello, World!" << std::endl;
}
and the python file,
from ctypes.util import find_library
import ctypes
import os
cwd = os.getcwd()
lib = f'{cwd}/cmake-build-debug/libDENCLUS.dylib'
if find_library(lib):
libx = ctypes.cdll.LoadLibrary(lib)
libx.hello()
else:
raise OSError("Could not find lib.")
ctypes find_library
returns None
and the subsequent block which calls the function hello
is not executed if i specify the absolute path to the .dylib
file, or if I call it as find_library(DENCLUS)
or any similar permutation. How can I get my python code to find the library and call the function?
EDIT:
I can call the c++ function outside of the if block. I think there is an issue with find_library
on MacOS.