[PYTHON] Easy C / C ++ multilingual binding with CMake + SWIG

CMake and SWIG are now quite famous, but you can easily generate C / C ++ glue code by combining the two.

Sorry for the shabby content to conclude Advent Calendar 2013 ...

Use C ++ code from Python

Directory structure

Test program

CMakeList.txt


find_package(PythonLibs REQUIRED)
find_package(SWIG REQUIRED)
include(${SWIG_USE_FILE})
include(GenerateExportHeader)

include_directories(
    ${CMAKE_CURRENT_SOURCE_DIR}
    ${PROJECT_BINARY_DIR}
    ${PYTHON_INCLUDE_PATH}
)

set(EXAM_SRCS
    example.h
)

set(INTERFACE_FILES
    example.i
)

set_source_files_properties(${INTERFACE_FILES} PROPERTIES CPLUSPLUS   ON)
swig_add_module(example python ${INTERFACE_FILES}
    ${EXAM_SRCS}
)

swig_link_libraries(example
    ${PYTHON_LIBRARIES}
)

example.h


#pragma once
#include <string>
class ExampleClass{
    std::string m_msg;
public:
    ExampleClass() : m_msg("Hello World") { }
    const std::string& get_msg(){ return m_msg; }
    void set_msg(const std::string &msg){ m_msg = msg; }
};

example.i


%module example
%include "std_string.i"

%{
#define SWIG_FILE_WITH_INIT
%}
%{
#include "example.h"
%}

%include "example.h"

Build

$cd build && cmake .. && make

Run

$python
>>> import example
>>> e = example.ExampleClass()
>>> e.get_msg()
'Hello World'
>>> e.set_msg("FizzBuzz")
>>> e.get_msg()
'FizzBuzz'

In other languages

You can use it by specifying another language in CMakeLists.txt.

Recommended Posts

Easy C / C ++ multilingual binding with CMake + SWIG
Easy build of C ++ code with CMake on Docker
Easy Grad-CAM with pytorch-gradcam
Container-like # 1 made with C
Debugging C / C ++ with gdb
Container-like # 2 made with C
Easy debugging with ipdb
Easy TopView with OpenCV
Embed a Python interpreter into a C ++ app with pybind11 + cmake