Skip to content

Instantly share code, notes, and snippets.

@jweinst1
Created February 16, 2026 01:03
Show Gist options
  • Select an option

  • Save jweinst1/3c7785f91b0108c0f0024271c4e30a5c to your computer and use it in GitHub Desktop.

Select an option

Save jweinst1/3c7785f91b0108c0f0024271c4e30a5c to your computer and use it in GitHub Desktop.
PyBind11 Example After brew install
#include <pybind11/pybind11.h>
#include "kvstore.h"
namespace py = pybind11;
PYBIND11_MODULE(kvstore, m) {
py::class_<KVStore>(m, "KVStore")
.def(py::init<const std::string&>(), py::arg("path"))
.def("put", &KVStore::put)
.def("get", &KVStore::get);
}
cmake_minimum_required(VERSION 3.14)
project(kvstore_python LANGUAGES CXX)
# ----------------------------
# 1) Find Python
# ----------------------------
find_package(Python COMPONENTS Interpreter Development REQUIRED)
message(STATUS "Python executable: ${Python_EXECUTABLE}")
message(STATUS "Python include dirs: ${Python_INCLUDE_DIRS}")
# ----------------------------
# 2) Find pybind11
# ----------------------------
# Option 1: Installed via pip
# You can set PYBIND11_DIR to your local pybind11 install
find_package(pybind11 CONFIG REQUIRED)
message(STATUS "Found pybind11: ${pybind11_INCLUDE_DIRS}")
# ----------------------------
# 3) Define extension module
# ----------------------------
pybind11_add_module(kvstore
src/bindings.cpp
src/kvstore.h
)
# ----------------------------
# 4) Set C++ standard
# ----------------------------
target_compile_features(kvstore PUBLIC cxx_std_17)
# Optional: add optimization flags
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif()
#include <optional>
#include <unordered_map>
#include <string>
class KVStore {
public:
KVStore(std::optional<std::string> path = std::nullopt) {
if (path) {
file_path = *path;
} else {
file_path = "in_memory";
}
}
void put(const std::string& key, const std::string& value) {
store[key] = value;
}
std::string get(const std::string& key) const {
auto it = store.find(key);
if (it != store.end()) return it->second;
return "";
}
private:
std::unordered_map<std::string, std::string> store;
std::string file_path;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment