I have the following files for generating a Python binding to a C++ project with SWIG and CMake:
test.h
int add(int a, int b);
test.cpp
int add(int a, int b)
{
return a+b;
}
test.i
%module test
%{
#include "test.h"
%}
CMakeLists.txt
cmake_minimum_required(VERSION 2.6)
project(swig-test)
# This is a CMake example for Python
add_library(testcpp SHARED test.cpp)
FIND_PACKAGE(SWIG REQUIRED)
INCLUDE(${SWIG_USE_FILE})
FIND_PACKAGE(PythonLibs)
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
SET(CMAKE_SWIG_FLAGS "")
SET_SOURCE_FILES_PROPERTIES(test.i PROPERTIES CPLUSPLUS ON)
SET_SOURCE_FILES_PROPERTIES(test.i PROPERTIES SWIG_FLAGS "-includeall")
set(${CMAKE_CXX_FLAGS} "${CMAKE_CXX_FLAGS} -fPIC")
SWIG_ADD_MODULE(test python test.i)
SWIG_LINK_LIBRARIES(test testcpp)
It compiles successfully and libtestcpp.so, _test.so, and test.py are created. strings libtestcpp.so and strings _test.so both have an entry _Z3addii and import test works in Python, but there is nothing under the test namespace in Python.
I've also tried manually compiling with
swig -c++ -python test.i
g++ -c -fpic test.cpp test_wrap.cxx -I/usr/include/python2.7 -I.
g++ -shared test.o test_wrap.o -o _test.so
with the same result.
It may be useful to note that import test isn't a completely empty module; import test; dir(test) yields
['__builtin__',
'__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'_newclass',
'_object',
'_swig_getattr',
'_swig_property',
'_swig_repr',
'_swig_setattr',
'_swig_setattr_nondynamic',
'_test']
and import test; help(test) has a description that it is created by SWIG.
%include "test.h"at the end intest.i.