我想通过 Cython 传递它的指针,在 C++ 中使用 bool 类型的 numpy 数组。我已经知道如何使用其他数据类型,如 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)
如果您需要更多信息,请告诉我。谢谢!