C++模板通过Cython运行
C++ template functions through Cython
我用模板化函数生成了一个简单的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)
相关文章:
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 代码在main()中运行,但在函数中出现错误
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何在运行中期切换GTK CSS style_context
- 如何在MS Visual Studio 2019中运行QT UI
- 如何通过cpp程序运行shell脚本
- IPC使用多个管道和分支进程来运行Python程序
- 删除指向指针的指针是运行时错误吗
- 如何用参数值调用函数(仅在运行时已知)
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- c++中的指针和运行时错误
- 使用C++(Cython)中的参数运行已编译的python脚本
- Cython Cmake模块运行时错误
- C++模板通过Cython运行
- 如何在运行时在通过 Cython 导入的 c++ 头文件中设置常量