C ++模板通过Cython运行

时间:2014-12-02 12:37:27

标签: c++ python-2.7 cython

我生成了一个带有模板化函数的简单C ++头文件lerp1d.h及其定义

lerp1d.h:

template <typename T> std::vector<T> LinearInterp(std::vector<T> x_data, std::vector<T> x_target, std::vector<T> f_vals) {
...}

然后我想用Cython编译这个函数并在python程序中与numpy一起使用它,基本的想法是与绘图工具等一起测试它。

所以我继续创建了以下文件:

cy_lerp1d.pyx:

# distutils: language = c++
# distutils: sources = lerp1d.
import Cython
cimport numpy as np

cdef extern from "<vector>" namespace "std":
    cdef cppclass vector [T]:
        cppclass iterator:
            T operator*()
            iterator operator++()
            bint operator==(iterator)
            bint operator!=(iterator)
            vector()
            void push_back(T&)
            T& operator[](int)
            T& at(int)
            iterator begin()
            iterator end()

cdef extern from "lerp1d.h":
    cdef vector[double] LinearInterp(vector[double]&, vector[double]&, vector[double]&)

据我所知,最后一个语句为double创建了一个模板实例化,Next

setup.py:

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
import os

os.environ["CC"]  = "g++ -std=c++11 -Wall"
os.environ["CXX"] = "g++ -std=c++11 -Wall"

#To build call with $python setup build_ext -i
setup(name = 'cy_lerp1d', ext_modules = 
    [Extension("cy_lerp1d", sources=["cy_lerp1d.pyx"],
     language = "c++" , include_dirs = [numpy.get_include()],
     cmdclass = {'build_ext' : build_ext})

最后是测试代码:

import numpy as np
import matplotlib.pyplot as plt
from cy_lerp1d import * #LinearInterp

if __name__ == '__main__':
    Some code...

我用python setup.py build_ext -i构建了Cython扩展,它没有错误 但是,当我尝试运行测试时,我得到了

 NameError: name 'LinearInterp' is not defined

如果在import语句中我从cy_lerp1d导入LinearInterp,我得到:

ImportError: cannot import name LinearInterp

到目前为止,我恐怕找不到与此情况相关的任何内容,欢迎任何帮助。

1 个答案:

答案 0 :(得分:0)

我很抱歉这是测试代码中的错误。除此之外,这似乎是一种有效的方法。另外需要注意的是,在.pyx模块中,必须对一个将作为包装器的python函数进行定义,无法直接调用cpp函数,所以在cy_lerp1d.pyx中:我添加了:

def LinearInterpCPP(x_v, x_t, f):
    return LinearInterp(x_v, x_t, f)
相关问题