Swig
Revision as of 17:52, 1 February 2012 by Colettace (talk | contribs) (→Compiling a C++ example for python on mac os 10.6)
Compiling a C++ example for python on mac os 10.6
- learning_swig.i
/* File : learning_swig.i */ /* Use c-style comments, because these lines get copied into the generated c code */ /* module name specified by %module directive */ %module learning_swig %{ /* The lines inside between the %{ }% aren't parsed by SWIG, but are copied verbatim into the wrapper c-code */ /* Put headers and other declarations here */ #include "learning_swig.hxx" /* extern keyword is optional for function prototypes... */ extern void print_my_info( char * the_name, double the_age ); /* ...but is required for variables */ extern char * my_name; extern double my_age; %} %include "learning_swig.hxx" /* ANSI C/C++ declarations go here */ extern void print_my_info( char * the_name, double the_age ); extern char * my_name; extern double my_age; extern class person;
- learning_swig.hxx
class person { public: person() : m_name( "Blank Person" ), m_age(-1) {} person( char * the_name, double the_age) : m_name( the_name ), m_age( the_age ) {} ~person() {} void print_all_info(); private: char * m_name; double m_age; };
- learning_swig.cxx
#include <stdio.h> #include "learning_swig.hxx" char * my_name = "Chris Coletta"; double my_age = 28.9; void print_my_info( char* the_name, double the_age ) { printf( "%s is %0.3f years old.\n", the_name, the_age ); } void person::print_all_info() { print_my_info( m_name, m_age ); }
- compilation
swig -c++ -python learning_swig.i g++ -c `python-config --cflags` learning_swig.cxx learning_swig_wrap.cxx g++ -bundle `python-config --ldflags` learning_swig.o learning_swig_wrap.o -o _learning_swig.so
- operation in ipython
import learning_swig learning_swig.print_my_info( "poop", 70 ) print learning_swig.cvar.my_age
- note: global variables are grouped into the "cvar" scope