pybind11 사용하기

안녕하세요 pybind11은 c++의 함수등을 python에서 사용할 수 있도록 즉, C/C++ 와Python을 연동해줄 수 있는 방법 중의 하나입니다.

이러한 pybind11을 사용하는 법을 정리해볼까 합니다.

https://wikidocs.net/159513

우선 이 링크를 참고했습니다.

우선 cmake로 다음과 같은 CMakeLists.txt를 작성합니다.

# CMakeLists.txt
cmake_minimum_required(VERSION 3.19)
project(example LANGUAGES CXX)


set(PYBIND11_FINDPYTHON ON)  # Python 찾기 활성화 (중요!)
set(CMAKE_PREFIX_PATH "Q:/Coding/20250819/venv/Lib/site-packages/pybind11")
find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)

pybind11_add_module(example main.cpp)


#"Q:\Coding\20250819\venv\Scripts\python.exe"

“Q:\Coding\20250819\venv\Scripts\python.exe” 는 제 가상환경 파이썬 인터프리터 경로입니다.

까먹지 않으려고 적어두었습니다.

여기서 CMAKE_PREFIX_PATH는 pybind11의 include 나 Lib등이 들어간 경로를 뜻합니다.

즉 주어진 그 경로를 시작점으로 나머지 include 등을 찾겠다는 의미입니다.

// main.cpp
#include <pybind11/pybind11.h>

namespace py = pybind11;

int add(int i, int j) {  return i + j; }
int sub(int i, int j) {  return i - j; }

struct MyData
{
  float x, y;

  MyData() : x(0), y(0) { }
  MyData(float x, float y) : x(x), y(y) { }

  void print() { printf("%f, %f\n", x, y); }
};

PYBIND11_MODULE(example, m) {          // "example" module name should be same of module name in CMakeLists
  m.doc() = "pybind11 example plugin"; // optional module docstring

  m.def("add", &add, "A function that adds two numbers");
  m.def("sub", &sub, "A function that subtracts two numbers");

  py::class_<MyData>(m, "MyData")
    .def(py::init<>())
    .def(py::init<float, float>(), "constructor 2", py::arg("x"), py::arg("y"))
    .def("print", &MyData::print)
    .def_readwrite("x", &MyData::x)
    .def_readwrite("y", &MyData::y);
}

이 코드는 제가 짠 코드가 아닙니다.

이 코드를 main.cpp로 CMakeLists.txt가 저장된 디렉터리 상에 같이 배치합니다.

mkdir build
cd build

대략 이렇게 됩니다.

이제

cmake .. -DCMAKE_BUILD_TYPE=Release -DPYTHON_EXECUTABLE="Q:\Coding\20250819\venv\Scripts\python.exe"

파이썬 경로를 -DPYTHON_EXECUTABLE에 할당해서 Release 모드로 상위디렉터리에 있는 CMakeLists.txt의 설계도 대로 작업합니다.

cmake --build . --config Release

이제 작업된 완성물을 Release모드로 빌드하는 절차를 거칩니다.

위의 절차를 끝마치면 다음과 같이 됩니다.

Release에 들어가 보면

다음과 같이 *.pyd파일이 존재하게 됩니다. 이 파일은 파이썬에서 사용하는 동적 링크 라이브러리입니다.

따라서 가상환경이 활성화된 상태에서 import를 해보면 됩니다.

정상적으로 import되어 python에서 c++의 함수를 사용할 수 있게 되었습니다.

https://medium.com/@ahmedfgad/handling-python-numpy-arrays-in-c-using-pybind11-0b7450f4f4b3

위 링크는 pybind와 numpy에 대한 훌륭한 인사이트를 설명하고 있다.