将 C++11 数组与 Cython 接口 [英] Interfacing C++11 array with Cython

查看:42
本文介绍了将 C++11 数组与 Cython 接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于构建 C++ 程序并在 Cython 中获取它,但在这里我试图获取 C++ 11 array 并且它绝对不起作用.

I am used to build C++ programs and get it in Cython, but here I am trying to get the C++ 11 array and it definitely doesn't work.

这是我的 .pxd :

Here is my .pxd :

cdef extern from "<array>" namespace "std" nogil :
    cdef cppclass array[T, size_t]:
        ctypedef T value_type
        cppclass iterator:
            T& operator*()
            iterator operator++()
            iterator operator--()
            iterator operator+(size_t)
            iterator operator-(size_t)
        bint operator==(iterator)
        bint operator!=(iterator)
        bint operator<(iterator)
        bint operator>(iterator)
        bint operator<=(iterator)
        bint operator>=(iterator)
        T& operator[](size_t)
        array() except +
        array(array&) except +

这个文件的大部分内容是从vector.pxd"改编的,但我删除了分配器,因为 c++11 array 不需要它.我使用 size_t 作为第二个模板参数,但我不确定.

Most of this file is an adaptation from "vector.pxd", but I removed the allocator because c++11 array doesn't need it. I used size_t as second template argument but I am not sure about it.

问题是,当我这样做时:

The problem is, when I do :

    from array11 cimport array
    cdef array[int, 5] test   

我明白了,编译时:

模板参数中的未知类型

如果我这样做:

    from array11 cimport array
    cdef array[int, 5] * test = new array[int, 5]()

我明白了:

new 运算符只能应用于 C++ 类

new operator can only be applied to a C++ class

知道我做错了什么吗?

谢谢!

推荐答案

正如评论中所讨论的,您遇到的问题是因为 Cython 并不真正支持非类型模板参数.一种解决方法(hacky 并且可能很脆弱)是欺骗 Cython 使其认为它提供了一个类型模板参数:

As discussed in the comments, the issue you're having is because Cython doesn't really support non-type template arguments. A workround (hacky and probably fragile) is to trick Cython into thinking it's providing a type template argument:

cdef extern from "<array>" namespace "std" nogil :
    cdef cppclass two "2":
        pass

    cdef cppclass array[T, U]:
        T& operator[](size_t)
        # this is obviously very very cut down

def f():
    cdef array[int,two] x
    return x[0]+x[1]

诀窍在于,如果您执行 cdef cppclass name "somestring" Cython 将盲目地将 somestring 替换为 name,从而生成正确的 C++ 代码.这种方法显然有一些限制,但对于简单的使用来说应该没问题.

The trick is that if you do cdef cppclass name "somestring" Cython will just blindly replace somestring for name, which generates the correct C++ code. There are obviously some limitations with this approach but for simple usage it should be fine.

这篇关于将 C++11 数组与 Cython 接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆