Skip to content

Instantly share code, notes, and snippets.

@nschloe
Created September 1, 2016 13:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nschloe/3d8bc8a22a1bea81237c0db2c4af7a1f to your computer and use it in GitHub Desktop.
Save nschloe/3d8bc8a22a1bea81237c0db2c4af7a1f to your computer and use it in GitHub Desktop.
SWIG Python: Derive from C++ base class in Python
cmake_minimum_required(VERSION 3.0)
project(mytest)
FIND_PACKAGE(SWIG REQUIRED)
INCLUDE(${SWIG_USE_FILE})
if (NOT MSVC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
endif()
FIND_PACKAGE(PythonLibs 2 REQUIRED)
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
SET(CMAKE_SWIG_FLAGS "-keyword")
SET_SOURCE_FILES_PROPERTIES(mytest.i PROPERTIES CPLUSPLUS ON)
SWIG_ADD_MODULE(mytest python mytest.i)
SWIG_LINK_LIBRARIES(
mytest
${PYTHON_LIBRARIES}
)
#ifndef MYTEST_HPP
#define MYTEST_HPP
#include <iostream>
#include <vector>
#include <memory>
class MyBaseClass {
public:
virtual
double
eval(const double x) const = 0;
};
class Square: public MyBaseClass {
public:
virtual
double
eval(const double x) const
{
return x*x;
}
};
void
mytest(const std::shared_ptr<MyBaseClass> & a) {
std::cout << a->eval(1.0) << std::endl;
std::cout << a->eval(2.0) << std::endl;
std::cout << a->eval(3.0) << std::endl;
}
#endif // MYTEST_HPP
%module mytest
%{
#define SWIG_FILE_WITH_INIT
#include "mytest.hpp"
%}
%include <std_shared_ptr.i>
%shared_ptr(MyBaseClass);
%shared_ptr(Square);
%include "mytest.hpp"
import mytest
a = mytest.Square()
mytest.mytest(a)
class Cube(mytest.MyBaseClass):
def __init__(self):
return
def eval(self, x):
return x*x*x
c = Cube()
mytest.mytest(c)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment