Skip to content

Instantly share code, notes, and snippets.

@YannickJadoul
Last active December 3, 2018 16:12
Show Gist options
  • Select an option

  • Save YannickJadoul/5f99abf44696088027a8a4a5dd224198 to your computer and use it in GitHub Desktop.

Select an option

Save YannickJadoul/5f99abf44696088027a8a4a5dd224198 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(); });
}
cmake_minimum_required(VERSION 3.8)
project(SharedDataPybind11)
add_subdirectory(pybind11)
add_library(SharedCounter SHARED SharedCounter.cpp)
target_compile_features(SharedCounter PUBLIC cxx_std_11)
if (WIN32)
target_compile_definitions(SharedCounter PRIVATE SharedCounter_EXPORTS)
endif()
pybind11_add_module(foo foo.cpp)
target_link_libraries(foo PRIVATE SharedCounter)
pybind11_add_module(bar bar.cpp)
target_link_libraries(bar PRIVATE SharedCounter)
#include <pybind11/pybind11.h>
#include "SharedCounter.h"
PYBIND11_MODULE(foo, m) {
m.def("inc", []() { return SharedCounter::getInstance().inc(); });
}
#include "SharedCounter.h"
SharedCounter &SharedCounter::getInstance() {
static SharedCounter instance;
return instance;
}
#ifdef _WIN32
# ifdef SharedCounter_EXPORTS
# define SharedCounter_EXPORT __declspec( dllexport )
# else
# define SharedCounter_EXPORT __declspec( dllimport )
# endif
#else
# define SharedCounter_EXPORT
#endif
class SharedCounter_EXPORT 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