Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a C++ module part of a Python package

I have the following directory layout

awesome_package
\- module1.py
\- build
   \- module2.so

I currently import module1 as

import awesome_package.module1

and module2 as

import sys
sys.path.append('path/to/awesome_package/build')
import module2

but I would like to be able to use the former syntax.

module2 is created by pybind11 in a fashion like:

PYBIND11_MODULE(module2, module2) {
    module2.doc() = "C++ module wrapped for Python";
    module2.def("some_cpp_function", some_cpp_function) 
}
like image 801
user357269 Avatar asked Aug 10 '17 15:08

user357269


1 Answers

As I said in my comment, binary Python modules are normally built with distutils/setuptools. For that you need to write setup.py script with all necessary options. Below is a very minimal example showing only basic things:

from setuptools import setup, Extension

setup(
    name = 'awesome',
    version = '0.0.1',
    packages = ['awesome_package']                     
    ext_modules = [Extension(
       'awesome_package.module2',
       ['src/module2.cpp']
    )]
)

Naturally, in setup.py you need to specify all your build options like header files, compiler flags etc.

If you insist on using CMake, you need to add a custom copy command to copy your compiled module inside your package. Something like this:

add_custom_command(TARGET module2 POST_BUILD
       COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:module2>
       "${CMAKE_SOURCE_DIR}/awesome_package"
    )
like image 146
Roman Miroshnychenko Avatar answered Oct 14 '22 07:10

Roman Miroshnychenko