代码之家  ›  专栏  ›  技术社区  ›  SEU

Python的MEX等价物(C包装函数)

  •  2
  • SEU  · 技术社区  · 14 年前

    来自MATLAB,我正在寻找一些在Python中创建函数的方法,这些函数是从包装C函数派生的。我偶然发现了Cython、ctypes和SWIG。我的意图不是通过任何因素来提高速度(尽管这肯定会有所帮助)。

    有人能为这样的目的推荐一个像样的解决方案吗。 编辑:做这份工作最受欢迎/采用的方式是什么?

    谢谢

    1 回复  |  直到 14 年前
        1
  •  1
  •   jmetz    14 年前

    我发现了 weave 适用于较短的函数,并且界面非常简单。

    为了让您了解界面的简单程度,以下是一个示例(取自 PerformancePython website )。请注意转换器是如何为您处理多维数组转换的(在本例中为Blitz)。

    from scipy.weave import converters
    
    def inlineTimeStep(self, dt=0.0):
        """Takes a time step using inlined C code -- this version uses
        blitz arrays."""
        g = self.grid
        nx, ny = g.u.shape
        dx2, dy2 = g.dx**2, g.dy**2
        dnr_inv = 0.5/(dx2 + dy2)
        u = g.u
    
        code = """
               #line 120 "laplace.py" (This is only useful for debugging)
               double tmp, err, diff;
               err = 0.0;
               for (int i=1; i<nx-1; ++i) {
                   for (int j=1; j<ny-1; ++j) {
                       tmp = u(i,j);
                       u(i,j) = ((u(i-1,j) + u(i+1,j))*dy2 +
                                 (u(i,j-1) + u(i,j+1))*dx2)*dnr_inv;
                       diff = u(i,j) - tmp;
                       err += diff*diff;
                   }
               }
               return_val = sqrt(err);
               """
        # compiler keyword only needed on windows with MSVC installed
        err = weave.inline(code,
                           ['u', 'dx2', 'dy2', 'dnr_inv', 'nx', 'ny'],
                           type_converters=converters.blitz,
                           compiler = 'gcc')
        return err