Created
September 1, 2016 13:02
-
-
Save nschloe/3d8bc8a22a1bea81237c0db2c4af7a1f to your computer and use it in GitHub Desktop.
SWIG Python: Derive from C++ base class in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%module mytest | |
%{ | |
#define SWIG_FILE_WITH_INIT | |
#include "mytest.hpp" | |
%} | |
%include <std_shared_ptr.i> | |
%shared_ptr(MyBaseClass); | |
%shared_ptr(Square); | |
%include "mytest.hpp" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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