将C ++ 11数组与Cython接口 [英] Interfacing C++11 array with Cython
问题描述
我习惯于构建C ++程序并在Cython中获得它,但是在这里,我试图获得C ++ 11 array
,它肯定不起作用。
这是我的.pxd:
cdef来自< array> ;名称空间 std nogil:
cdef cppclass array [T,size_t]:
ctypedef T value_type
cppclass迭代器:
T&运算符*()
迭代运算符++()
迭代运算符-()
迭代运算符+(size_t)
迭代运算符-(size_t)
二进制运算符==(迭代器)
二进制算子!=(迭代器)
二进制算子<(迭代器)
二进制算子>(迭代器)
二进制算子< ==(迭代器)
二进制算子> ; =(迭代器)
T& operator [](size_t)
array()除外+
array(array&)除外+
此文件的大部分内容来自 vector.pxd,但是我删除了分配器,因为c ++ 11 array
不需要它。我使用 size_t
作为第二个模板参数,但是我不确定。
问题是,当我这样做时:
from array11 cimport数组
cdef array [int,5]测试
编译时得到:
模板参数中的未知类型
如果我这样做:
from array11 cimport array
cdef array [ int,5] * test = new array [int,5]()
我得到了:
新运算符只能应用于C ++类
关于我在做什么错的任何想法吗?
谢谢!
如评论中所讨论,您遇到的问题是因为Cython并不真正支持非类型模板参数。一种变通方法(hacky,可能是脆弱的)是诱使Cython认为它正在提供类型模板参数:
cdef extern from< ; array>名称空间 std nogil:
cdef cppclass两个 2:
传递
cdef cppclass array [T,U]:
T& operator [](size_t)
#这显然是非常削减的
def f():
cdef array [int,two] x
return x [ 0] + x [1]
诀窍在于,如果您执行 cdef cppclass名称为 somestring
Cython会盲目地将 somestring
替换为name,从而生成正确的C ++代码。这种方法显然有一些局限性,但是对于简单的用法来说应该没问题。
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.
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 +
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
I get, when compiling :
unknown type in template argument
If I do :
from array11 cimport array
cdef array[int, 5] * test = new array[int, 5]()
I get :
new operator can only be applied to a C++ class
Any idea about what I am doing wrong?
Thanks!
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]
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屋!