首页 > 解决方案 > 在 cython 中包装类模板和函数模板

问题描述

我正在尝试用 cython 包装整个 c++ 模板库,以使其可供 python 用户使用。正如我已经提到的,该库是类和类方法的模板,因此,它不是编译的,而是“仅头文件”。由于这个库有点大,我决定创建一个文件作为起点,并尝试将它包装在 cython 中,让它作为 python 函数使用。该文件,让我们称之为easy.hpp,反映了库的编写方式

#include <iterator>
#include <utility>
#include <vector>
#include <iostream>

namespace exNamespace {

class exClass
{
public:
   template <typename T1, typename T2> void exMethod(T1 a, T2 b) const;
};

// Impl
template <typename T1, typename T2> void exClass::exMethod(T1 a, T2 b) const
{

    for(auto i=0; i< a.size(); i++){
        std::cout << a[i] << "-" << b[i] << "\n";
    }

    }
}

遵循“Kurt Smith 为 Python 程序员编写的 Cython-A 指南”,我构建了两个文件: tWrap.pxdtWrap.pyx

//tWrap.pxd
cdef extern from "easy.hpp" namespace "exNamespace":
    cdef cppclass exClass:
        void exMethod[T1,T2](T1 a, T2, b) except +

//tWrap.pyx
from libcpp.vector cimport vector
cimport tWrap


ctypedef vector[double].iterator vvit

cdef _process(v1, v2):
    cdef vector[double] vv1
    cdef vector[double] vv2
    assert len(v1) == len(v2)        
    for elt1 in v1:
        vv1.push_back(<double>elt1)
    for elt2 in v2:
        vv2.push_back(<double>elt2)
    exClass.exMethod(vv1.begin(),vv2.begin())

def process(v1,v2):
    _process(v1,v2)

setup.py写法如下:

import os

from setuptools import setup, Extension
from setuptools.dist import Distribution
from Cython.Distutils import build_ext

Distribution(dict(setup_requires='Cython'))

ext_modules = [
     Extension("test", ["tWrap.pyx"],
              language="c++"
            )
]

setup(
    include_package_data=True,
    package_data={'': ['*.pyx', '*.pxd', '*.h', '*.c']},
    cmdclass = {'build_ext': build_ext},
    ext_modules=ext_modules
) 

在编译阶段,我遇到了这些错误:

Error compiling Cython file:
------------------------------------------------------------
...
    assert len(v1) == len(v2)        
    for elt1 in v1:
        vv1.push_back(<double>elt1)
    for elt2 in v2:
        vv2.push_back(<double>elt2)
    exClass.exMethod(vv1.begin(),vv2.begin())
   ^
------------------------------------------------------------

tWrap.pyx:26:4: undeclared name not builtin: exClass

Error compiling Cython file:
------------------------------------------------------------
...
    assert len(v1) == len(v2)        
    for elt1 in v1:
        vv1.push_back(<double>elt1)
    for elt2 in v2:
        vv2.push_back(<double>elt2)
    exClass.exMethod(vv1.begin(),vv2.begin())
                             ^
------------------------------------------------------------

tWrap.pyx:26:30: Cannot convert 'iterator' to Python object

Error compiling Cython file:
------------------------------------------------------------
...
    assert len(v1) == len(v2)        
    for elt1 in v1:
        vv1.push_back(<double>elt1)
    for elt2 in v2:
        vv2.push_back(<double>elt2)
    exClass.exMethod(vv1.begin(),vv2.begin())
                                         ^
------------------------------------------------------------

tWrap.pyx:26:42: Cannot convert 'iterator' to Python object

我不得不承认没有完全理解如何在 cython 中管理模板,因为在书中作者总是从来自 std 库的模板函数开始。

我想实现类似:

import test
test.process([1,3,5],[2,4,6])

1-2
3-4
5-6

或使用带有可打印(<< 运算符)类型的 list(containers)。

更新

试图获得类的实例:

//tWrap.pyx
...
cdef class cClass:
    cdef tWrap.exClass *_thisptr
    def __cinit__(self):
        self._thisptr = new tWrap.exClass()
    def __dealloc__(self):
        if self._thisptr != NULL:
            del self._thisptr
...

    cdef _process(self,v1, v2):
        cdef vector[double] vv1
        cdef vector[double] vv2
        assert len(v1) == len(v2)        
        for elt1 in v1:
            vv1.push_back(<double>elt1)
        for elt2 in v2:
            vv2.push_back(<double>elt2)
        self._thisptr.exMethod(vv1.begin(),vv2.begin())
...

但是编译失败并出现此错误:

        self._thisptr.exMethod(vv1.begin(),vv2.begin())
                             ^
------------------------------------------------------------

tWrap.pyx:26:30: Call with wrong number of arguments (expected 3, got 2)

标签: pythonc++templatescython

解决方案


推荐阅读