I am trying to understand weave.inline to wrap C code in my Python programs. The code below simply takes the Numpy array and multiplicates all of its elements by 2.
inl.py
import numpy
import scipy.weave
a = numpy.array([1.0, 2.0, 3.0])
N = a.shape[0]
print a
code = \
"""
int i;
for(i = 0; i < N; i++)
{
a[i] = a[i] * 2;
}
"""
scipy.weave.inline(code, ['a','N'])
print a
Then I want to carry some functions from inline code to external libraries. Let it be the trivial multiplication by 2. So I create two files:
mult.c
#include "mult.h"
float mult(float n)
{
return n * 2;
}
mult.h
float inc(float n);
Now I want to use function mult in my inline code. But I don’t know how do I link my C files with Python inline code. I tried to compile C files as shared library and pass them as headers and libraries in weave, but that was in vain. Any suggestions?
I have successfully done this, calling math functions from R via weave.inline() code (under Ubuntu Linux).
First, compile your C functions as a shared library. In my case, I grabbed a recent release of R from CRAN, and did
You should now have a file called
libRmath.so. Iflibpathis a string with the directory that holdslibRmath.so, you can do something likeNote a couple things. The header declarations have to go in
support_code, notcode(I don’t know why), and they have to be prefixed withextern "C"because they’re C code, not C++ (this is standard). It should be possible to include headers files instead of usingsupport_code(check the docs for weave.inline), but I haven’t tried it. The library name isRmath, but the shared library file islibRmath.so, in the usual Unix convention. And the path to the library is specified twice, once for linking, and once for execution.Hope this helps!