Skip to content

Instantly share code, notes, and snippets.

@gdianaty
Last active April 19, 2020 01:50
Show Gist options
  • Save gdianaty/e6cc8e1f257ac8ae49e962f85c5554dc to your computer and use it in GitHub Desktop.
Save gdianaty/e6cc8e1f257ac8ae49e962f85c5554dc to your computer and use it in GitHub Desktop.
SWIG generation function for CMake
# Authored by Graham Dianaty for Bitlogix Technologies. ==========//
cmake_minimum_required(VERSION 3.13)
function(swig_generate_wrapper ARGS_SWIG ARGS_OUTDIR ARGS_INTERFACE)
find_program(SWIG "swig" "swig.exe") # this should probably be somewhere in PATH
set(SWIG_IN_FILE "${CMAKE_CURRENT_SOURCE_DIR}/${ARGS_INTERFACE}")
set(SWIG_OUT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/${ARGS_OUTDIR}")
# if we're getting no custom input directory, set to current dir.
if("${SWIG_OUT_DIR}" STREQUAL "CURRENT_SOURCE_DIR")
set(SWIG_OUT_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
endif()
if(SWIG)
message(DEBUG "SWIG found.")
else()
message(FATAL_ERROR "SWIG not found.")
endif()
# check our incoming file exists.
if(NOT EXISTS "${SWIG_IN_FILE}")
message(ERROR_FATAL "[SWIG] Interface file ${SWIG_IN_FILE} does not exist!")
endif()
# check that we're generating a .i file
get_filename_component(INFILE_EXT "${SWIG_IN_FILE}" EXT)
if(NOT "${INFILE_EXT}" STREQUAL ".i")
message(ERROR_FATAL "[SWIG] Interface file ${SWIG_IN_FILE} isn't an interface file, it ends in ${INFILE_EXT}!")
endif()
# everything looks good, let's execute SWIG:
exec_program(${SWIG} ${CMAKE_CURRENT_SOURCE_DIR}
ARGS "${SWIG_ARGS} -outdir ${SWIG_OUT_DIR} ${SWIG_IN_FILE}"
OUTPUT_VARIABLE SWIG_OUTPUT
)
message(DEBUG "[SWIG] ${SWIG_OUTPUT}")
message(STATUS "[SWIG] Generation of ${SWIG_IN_FILE} completed.")
endfunction(swig_generate_wrapper INTERFACE OUTDIR)

swig.cmake

A project I was working on recently in CMake required I build many SWIG interfaces, and I wanted a compact and clean way to do so. Below is a script that can be embeded in your CMake project to generate SWIG files based on your incoming arguments, as well as the signature for the function. This script assumes that you keep SWIG somewhere on your PATH. Note: It is your resposibility to compile the generated file(s). I recommend doing so with wildcards out of a personal preference.

swig_generate_wrapper(
ARGS_TO_SWIG - This represents the arguments you wish to pass to SWIG
OUTPUT_DIRECTORY - Where you want to generate new files. Set CURRENT_SOURCE_DIR to use current directory.
INPUT_FILE - The (relative!) path to the interface file you wish to compile.
)

Here is an example project that compiles a C++ wrap file with Node.JS:

...
project (my_cool_project)
swig_generate_wrapper("-c++ -javascript -jsc" "src" "src/my_cool_interface.i")
file(GLOB SOURCE_FILES "src/*.cpp" "src/*.h" "src/*.cxx")
add_library(${PROJECT_NAME} SHARED ${SOURCE_FILES})
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment