【问题标题】:Accessing C++ template class in cython在 cython 中访问 C++ 模板类
【发布时间】:2021-01-25 00:25:45
【问题描述】:

我在一个名为 containers.h 的文件中定义了一个名为 List 的模板类:

#include <iostream>
#include <vector>


namespace containers {
    template <class T> class List {
        private:
            std::vector<T> vector;
        public:
            List() {};
            ~List() {};
            void append(T* item) {
                vector.push_back(*item);
            }
            void print_items() {
                for ( T item : vector ) {
                    std::cout << item << std::endl;
                }
            }
    };
}

我正在尝试使用main.pyx 中的代码将此类导入 Cython:

#!python
# cython: language_level = 3
# distutils: language = c++


cdef extern from "containers.h" namespace "containers":
    cdef cppclass List[T]:
        List() except +
        void append(T *item)
        void print_items()


def test():
    cdef List[int] *l = new List[int]()
    cdef int i
    for i in range(10):
        l.append(&i)
    l.print_items()

这就是我尝试运行这段代码时发生的情况:

>>> import main
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: /home/arin/Desktop/Misc/test_cpp/main.cpython-38-x86_64-linux-gnu.so: undefined symbol: _ZN10containers4ListIiEC1Ev

为什么会出现此错误,如何解决?

【问题讨论】:

标签: python c++ templates cython


【解决方案1】:

这只是编译时的一个愚蠢的错误:在setup.py 中,我将"main.cpp" 传递给cythonize 函数而不是"main.pyx",它在编译时没有导致错误,因为我有另一个名为@987654325 的文件@。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 2010-12-08
    • 2019-05-28
    • 1970-01-01
    • 2012-02-01
    • 2021-03-21
    • 1970-01-01
    相关资源
    最近更新 更多