Skip to content

Instantly share code, notes, and snippets.

@phaustin
Forked from YannickJadoul/CMakeLists.txt
Last active December 2, 2018 21:18
Show Gist options
  • Save phaustin/b9458c9cab989c38bcac851c7b9d54d5 to your computer and use it in GitHub Desktop.
Save phaustin/b9458c9cab989c38bcac851c7b9d54d5 to your computer and use it in GitHub Desktop.
Shared data between two pybind11 modules
#include <pybind11/pybind11.h>
#include "SharedCounter.h"
PYBIND11_MODULE(bar, m) {
m.def("inc", []() { return SharedCounter::getInstance().inc(); });
}
g++ -shared SharedCounter.cpp -o libSharedCounter.so
g++ -O3 -Wall -shared -std=c++11 -fPIC -I. -I`python3-config --includes` foo.cpp -L. -lSharedCounter -o foo`python3-config --extension-suffix`
g++ -O3 -Wall -shared -std=c++11 -fPIC -I. -I`python3-config --includes` bar.cpp -L. -lSharedCounter -o bar`python3-config --extension-suffix`
LD_LIBRARY_PATH=`pwd` python3
cmake_minimum_required(VERSION 3.8)
project(example)
add_subdirectory(pybind11)
add_library(shared_counter SharedCounter.cpp)
target_compile_features(shared_counter PUBLIC cxx_std_11)
pybind11_add_module(foo foo.cpp)
target_link_libraries(foo PRIVATE shared_counter)
pybind11_add_module(bar bar.cpp)
target_link_libraries(bar PRIVATE shared_counter)
#include <pybind11/pybind11.h>
#include "SharedCounter.h"
PYBIND11_MODULE(foo, m) {
m.def("inc", []() { return SharedCounter::getInstance().inc(); });
}
gives me
[/c/Users/sam/Dropbox/pybind_example][sam] $ cat test.py
import foo
import bar
print(foo.inc())
print(bar.inc())
print(foo.inc())
print(bar.inc())
[/c/Users/sam/Dropbox/pybind_example][sam] $ python.exe test.py
0
0
1
1
#include "SharedCounter.h"
SharedCounter &SharedCounter::getInstance() {
static SharedCounter instance;
return instance;
}
class SharedCounter {
public:
static SharedCounter &getInstance();
int inc() { return m_counter++; }
private:
SharedCounter() = default;
int m_counter;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment