2013-08-05 3 views
10

Cython経由でポインタを渡すことで、C++でbool型のnumpy配列を使いたいと思っています。私はすでにuint8のような他のデータ型でそれを行う方法を知っています。ブーリアンと同じ方法でやっても動作しません。私はコンパイルすることができていますが、以下の例外が実行時に存在している:ここではnumpyポインタ(dtype = np.bool)をC++に渡す

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) 

詳細情報が必要な場合はお知らせください。ありがとうございました!

答えて

9

問題は配列型宣言にあるようです。 https://cython.readthedocs.org/en/latest/src/tutorial/numpy.htmlのドキュメントによれば、ブール値のアレーはまだサポートされていませんが、符号なし8ビット整数の配列としてキャストすることで使用できます。 はここでは、ブール値の1次元配列あなたは何をしているかに応じて、あなたのC++コードで

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 

、(希望ブールnumpyのアレイのsum()方法と同じ)の合計を取る簡単な例だあなたboolにポインタを戻す必要があるかもしれませんが、私はそれについては分かりません。

編集:ここでは、Cythonでポインタをキャストする方法の例を示します。 まだ配列を符号なし8ビット整数として入力する必要がありましたが、次にポインタをboolにキャストし直しました。あなたはポインタとしてで配列を渡したい場合は

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ファイルに次の関数を使用することができます。

arptr(&A[0]) 
として呼び出すことができ

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

関連する問題