gpt4 book ai didi

c++ - 将 numpy 指针 (dtype=np.bool) 传递给 C++

转载 作者:IT老高 更新时间:2023-10-28 23:18:25 27 4
gpt4 key购买 nike

我想在 C++ 中使用 bool 类型的 numpy 数组,方法是通过 Cython 传递它的指针。我已经知道如何使用其他数据类型,如 uint8。用 boolean 做同样的事情是行不通的。我可以编译,但运行时出现以下异常:

Traceback (most recent call last):
File "test.py", line 15, in <module>
c = r.count(b, 4)
File "rect.pyx", line 41, in rect.PyRectangle.count (rect.cpp:1865)
def count(self, np.ndarray[bool, ndim=1, mode="c"] array not None, int size):
ValueError: Does not understand character buffer dtype format string ('?')

这是我的 c++ 方法:

void Rectangle::count(bool * array, int size)
{
for (int i = 0; i < size; i++){
std::cout << array[i] << std::endl;
}
}

Cython 文件:

# distutils: language = c++
# distutils: sources = Rectangle.cpp

import numpy as np
cimport numpy as np

from libcpp cimport bool

cdef extern from "Rectangle.h" namespace "shapes":
cdef cppclass Rectangle:
Rectangle(int, int, int, int) except +
int x0, y0, x1, y1
void count(bool*, int)

cdef class PyRectangle:
cdef Rectangle *thisptr # hold a C++ instance which we're wrapping
def __cinit__(self, int x0, int y0, int x1, int y1):
self.thisptr = new Rectangle(x0, y0, x1, y1)
def __dealloc__(self):
del self.thisptr

def count(self, np.ndarray[bool, ndim=1, mode="c"] array not None, int size):
self.thisptr.count(&array[0], size)

这里是调用该方法并产生错误的python脚本:

import numpy as np
import rect

b = np.array([True, False, False, True])
c = r.count(b, 4)

如果您需要更多信息,请告诉我。谢谢!

最佳答案

看起来问题出在数组类型声明上。根据 https://cython.readthedocs.org/en/latest/src/tutorial/numpy.html 上的文档尚不支持 boolean 数组,但您可以通过将它们转换为无符号八位整数数组来使用它们。这是一个简单的示例,它采用一维 boolean 值数组的总和(与 boolean NumPy 数组的 sum() 方法相同)

from numpy cimport ndarray as ar
cimport numpy as np
cimport cython

@cython.boundscheck(False)
@cython.wraparound(False)
def cysum(ar[np.uint8_t,cast=True] A):
cdef int i, n=A.size, tot=0
for i in xrange(n):
tot += A[i]
return tot

在您的 C++ 代码中,根据您正在执行的操作,您可能需要将指针转换回 boolean 值,我不确定。

编辑:这是一个如何在 Cython 中转换指针的示例,它应该可以满足您的需求。我仍然必须将数组键入为无符号 8 位整数,但我随后将指针转换回 boolean 值。

from numpy cimport ndarray as ar
cimport numpy as np
from libcpp cimport bool
cimport cython

def cysum(ar[np.uint8_t,cast=True] A):
cdef int i, n=A.size, tot=0
cdef bool *bptr
bptr = <bool*> &A[0]
for i in xrange(n):
tot += bptr[i]
return tot

如果您想将数组作为指针传入,您可以在 Cython 文件中使用以下函数:

cdef bool* arptr(np.uint8_t* uintptr):
cdef bool *bptr
bptr = <bool*> uintptr
return bptr

可以称为

arptr(&A[0])

关于c++ - 将 numpy 指针 (dtype=np.bool) 传递给 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18058744/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com