Skip to content

Instantly share code, notes, and snippets.

@WimPessemier
Created February 25, 2014 19:03
Show Gist options
  • Save WimPessemier/9215381 to your computer and use it in GitHub Desktop.
Save WimPessemier/9215381 to your computer and use it in GitHub Desktop.
Typemaps problem
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
#ifndef KOMPLEX_H_
#define KOMPLEX_H_
struct Komplex
{
Komplex() : real(0.0), imag(0.0) {}
double real;
double imag;
};
#endif /* KOMPLEX_H_ */
%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>;
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