Skip to content

Instantly share code, notes, and snippets.

@Bktero
Created December 10, 2018 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bktero/233ba1aa4b5edcb943add69e7d4ee362 to your computer and use it in GitHub Desktop.
Save Bktero/233ba1aa4b5edcb943add69e7d4ee362 to your computer and use it in GitHub Desktop.
[C++][Python] Create Python module with C++ and boost::python
cmake_minimum_required(VERSION 3.10)
project(Boost_Python_Example)
# Find Boost
find_package(Boost COMPONENTS python3)
# Find Python
find_package(PythonInterp 3 REQUIRED)
find_package(PythonLibs 3 REQUIRED)
# Create library
add_library(mylibrary SHARED functions.cpp)
target_include_directories(mylibrary
PRIVATE ${Boost_INCLUDE_DIRS} ${PYTHON_INCLUDE_DIRS})
target_link_libraries(mylibrary ${Boost_LIBRARIES})
# Don't use the default 'lib' prefix
set_target_properties(mylibrary PROPERTIES PREFIX "")
message("install ${Python_SITELIB}")
#include <boost/python.hpp>
#include <iostream>
static int compute(int a, int b) {
return (a + b) * (a - b );
}
static void sayHello() {
std::cout << "Hello\n";
}
static void sayHelloTo(const std::string& person) {
std::cout << "Hello, " << person << '\n';
}
class Printer {
public:
Printer(const std::string& name) :
name_m(name) {
}
void print(const std::string& text) {
std::cout << '[' << name_m << ']' << text << '\n';
}
private:
std::string name_m;
};
BOOST_PYTHON_MODULE(mylibrary)
{
using namespace boost::python;
def("compute", compute);
def("say_hello", sayHello); // Python name != C++ name
def("sayHelloTo", sayHelloTo);
class_<Printer>("Printer", init<const std::string&>())
.def("print", &Printer::print);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment