1

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.

3
  • 2
    I think you still need to add a line %include "test.h" at the end in test.i. Commented Nov 14, 2016 at 21:49
  • That is indeed correct -- I seem to have completely overlooked that! Commented Nov 14, 2016 at 23:40
  • I wasn't 100% sure before I commented. I converted my comment to an answer. Commented Nov 15, 2016 at 3:03

1 Answer 1

2

You need to to add a line %include "test.h" at the end in test.i

%module test
%{
#include "test.h"
%}

%include "test.h"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.