Skip to content

Instantly share code, notes, and snippets.

@philippslang
Last active December 29, 2015 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philippslang/a1d95f661524a2fed6bd to your computer and use it in GitHub Desktop.
Save philippslang/a1d95f661524a2fed6bd to your computer and use it in GitHub Desktop.
Basic how-to for C - Swig - Python/Numpy interfacing
void demo(size_t nr, size_t nc, double *arr)
{
for(int r(0); r < nr; ++r)
for(int c(0); c < nc; ++c)
arr[r*nc+c] = 1.; // fills arr[r][c]
}
#import demo
a = np.zeros((10,10))
demo.demo(a)
print a
/* Source.i */
/* module name needs be the name of the VS project in current setup */
%module demo
%{
/* only once in project/i files */
#define SWIG_FILE_WITH_INIT
/* headers as #include header.h or explicit declarations, only of functions that need interface */
extern void demo(size_t nr, size_t nc, double *arr);
%}
/* only once in project / i file */
%include "numpy.i"
%init %{
import_array();
%}
/* declare what interfaces to replace how - parameter names must be unique, replaced as given here for all */
%apply (int DIM1, int DIM2, double* INPLACE_ARRAY2) {(size_t nr, size_t nc, double *arr)};
/* now all that need interfaced, and replaced by above swig signature */
extern void demo(size_t nr, size_t nc, double *arr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment