Created
December 10, 2018 14:35
-
-
Save Bktero/233ba1aa4b5edcb943add69e7d4ee362 to your computer and use it in GitHub Desktop.
[C++][Python] Create Python module with C++ and boost::python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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