How do I use scipy.weave.inline together with external C libraries?

半腔热情 提交于 2019-12-07 01:31:08

问题


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?


回答1:


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

./configure --enable-R-static-lib --enable-static --with-readline=no
cd src/nmath/standalone/
make

You should now have a file called libRmath.so. If libpath is a string with the directory that holds libRmath.so, you can do something like

code = 'return_val = pbinom(100, 20000, 100./20000., 0, 1);'
support_code = 'extern "C" double pbinom(double x, double n, double p, int lower_tail, int log_p);'
weave.inline(code, support_code=support_code,
    library_dirs=[libpath], libraries=["Rmath"], runtime_library_dirs=[libpath])

Note a couple things. The header declarations have to go in support_code, not code (I don't know why), and they have to be prefixed with extern "C" because they're C code, not C++ (this is standard). It should be possible to include headers files instead of using support_code (check the docs for weave.inline), but I haven't tried it. The library name is Rmath, but the shared library file is libRmath.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!




回答2:


put the source of mult.c and mult.h in a string object called extra_code, then add the following line in your .weave invocation

support_code=extra_code,

there is also the option to include standard libraries as follows:

headers = ["<math.h>"]

enjoy



来源:https://stackoverflow.com/questions/4260528/how-do-i-use-scipy-weave-inline-together-with-external-c-libraries

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!