I have two C/C++ libraries which give interface to class Solver
and MultiSolver
derived from Solver
. I want make python API to both of them with minimum code repetition.
This means I don't want to copy/rewrite ctypes interface to function Solver
when writing interface to derived MultiSolver
. Currently I see 2 solutions:
- Wrap ctypes interface into python classes with hierarchy (but not very keen to do that, because it makes an other level of indirection)
- use
exec
command discussed here, but I think it is not very good practice - It is very much related to question about inheritance of python modules
Here is simplified example of the problem with only few functions in the library (in reality there are many more).
C/C++ side
Solver.h
class Solver{ public:
void solve(){ ... };
};
MultiSolver.h
#include "Solver.h"
class MultiSolver : public Solver { public:
void solve_multi(){ ... };
};
lib_commons.cpp
extern "C"{
void solve(){ W.solve(); };
}
libSolver.cpp
#include "Solver.h"
Solver W;
#include "lib_commons.cpp"
libMultiSolver.cpp
#include "MultiSolver.h"
MultiSolver W;
#include "lib_commons.cpp"
extern "C"{
void solve_multi(){ W.solve_multi(); };
}
Python side
libSolver.py
import ctypes
lib = ctypes.CDLL( path+"libSolver.so" )
lib.solve.argtypes = []
lib.solve.restype = None
def solve():
return lib.solve()
libMultiSolver.py
import ctypes
lib = ctypes.CDLL( path+"libMultiSolver.so" )
# ========== HERE ==========
# I don't want to repeate this !!!!!
lib.solve.argtypes = []
lib.solve.restype = None
def solve():
return lib.solve()
lib.solve_multi.argtypes = []
lib.solve_multi.restype = None
def solve_multi():
return lib.solve_multi()