本文介绍了我如何结合使用scipy.weave.inline与外部C库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解weave.inline包C $ C $下在我的Python程序。下面的code只需2取numpy的阵列和multiplicates的所有元素。

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

然后我想继续从内嵌code某些功能外部库。让它成为由2琐碎乘法所以我创建两个文件:

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);

现在我想使用的功能MULT在我的内联code。但我不知道我怎么联系与Python内嵌code我的C文件。我试图编译C文件作为共享库,并通过他们在编织头文件和库,但这是徒劳的。有什么建议?

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?

推荐答案

我已经成功地通过weave.inline做到了这一点,从研发调用数学函数()code(下Ubuntu Linux操作系统)。

I have successfully done this, calling math functions from R via weave.inline() code (under Ubuntu Linux).

首先,编译你的C函数作为共享库。就我而言,我抓住的R CRAN从近期发布,并没有

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

您现在应该有一个名为 libRmath.so 。如果 LIBPATH 是保存目录 libRmath.so ,你可以这样做。

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])

请注意两件事情。标题声明在 support_ code 来走,而不是 code (我不知道为什么),他们必须与的externC,因为它们是C code,不是C ++(这是标准)pfixed $ p $。它应该是可能的包括头文件,而不是使用 support_ code (检查weave.inline的文档),但我还没有尝试过。库名称是 Rmath ,但共享库文件是 libRmath.so ,在普通的Unix约定。和路径库是连接的,一旦执行指定了两次,一次。

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.

希望这有助于!

这篇关于我如何结合使用scipy.weave.inline与外部C库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 20:04
查看更多