C++模板通过Cython运行

C++ template functions through Cython

本文关键字:Cython 运行 C++      更新时间:2023-10-16

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

勒普1d.h:

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

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

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

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

据我了解,最后一条语句为双精度创建了一个模板实例化,下一个

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...

我用以下内容构建 Cython 扩展: python setup.py build_ext -i 它没有给出任何错误但是,当我尝试运行测试时,我得到

 NameError: name 'LinearInterp' is not defined

如果在导入语句中我从导入线性Interp cy_lerp1d我得到:

ImportError: cannot import name LinearInterp

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

我很

抱歉这是测试中代码的错误。除此之外,这似乎是一种有效的方法。另一件需要注意的事情是,在 .pyx 模块中,必须定义一个将充当包装器的 python 函数,无法直接调用 cpp 函数,因此在 cy_lerp1d.pyx 中: 我补充说:

def LinearInterpCPP(x_v, x_t, f):
    return LinearInterp(x_v, x_t, f)