Created
February 25, 2014 19:03
-
-
Save WimPessemier/9215381 to your computer and use it in GitHub Desktop.
Typemaps problem
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
g++ -fno-strict-aliasing komplex.h -o komplex.so | |
swig -c++ -python -modern -extranative -o myproject_wrap.cpp myproject.i | |
g++ -fno-strict-aliasing -fpic -shared -I/usr/include/python2.7/ -I. myproject_wrap.cpp -o _myproject.so |
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 KOMPLEX_H_ | |
#define KOMPLEX_H_ | |
struct Komplex | |
{ | |
Komplex() : real(0.0), imag(0.0) {} | |
double real; | |
double imag; | |
}; | |
#endif /* KOMPLEX_H_ */ |
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 myproject | |
%{ | |
#include "komplex.h" | |
%} | |
%typemap(typecheck) Komplex& | |
{ | |
PyComplex_Check($input) ? 1 : 0; | |
} | |
%typemap(in) Komplex& (Komplex temp) | |
{ | |
temp.real = PyComplex_RealAsDouble($input); | |
temp.imag = PyComplex_ImagAsDouble($input); | |
$1 = &temp; | |
} | |
%typemap(out) Komplex& | |
{ | |
$result = PyComplex_FromDoubles($1->real, $1->imag); | |
} | |
// define a vector of the wrapped class: | |
%include "std_vector.i" | |
%template(KomplexVector) std::vector<Komplex>; |
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 myproject | |
# fill a vector (the "typecheck" and "in" typemaps are used!) | |
vec = myproject.KomplexVector() | |
vec.append( complex(1,2) ) | |
# below, the output typemap is used: | |
print("First attempt:") | |
for i in xrange(len(vec)): | |
print(vec[i]) # prints: (1+2j) | |
assert vec[i] == complex(1,2) # OK | |
# below, the output typemap is NOT used: | |
print("Second attempt:") | |
for k in vec: | |
print(k) # prints: <Swig Object of type 'Komplex *' at 0x7f0194c6de10> | |
assert k == complex(1,2) # fails! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment