2016-07-10 37 views

回答

2

你應該能夠就好像他們」只定義了內部函數在Cython中重新使用普通的C函數。喜歡的東西

cdef extern from "emmintrin.h": # I'm going off the microsoft documentation for where the headers are 
    # define the datatype as an opaque type 
    ctypedef struct __m128i x: 
     pass 

    __m128i _mm_set_epi32 (int i3, int i2, int i1, int i0) 

cdef extern from "wmmintrin.h": 
    __m128i _mm_aesdec_si128(__m128i v,__m128i rkey) 

# then in some Cython function 
def f(): 
    cdef __m128i v = _mm_set_epi32(1,2,3,4) 
    cdef __m128i key = _mm_set_epi32(5,6,7,8) 
    cdef __m128i result = _mm_aesdec_si128(v,key) 

這個問題:「我如何應用此過bytes陣」?首先,你得到一個字節數組的char*。然後用range迭代它(注意不要跑到最後)。

# assuming you already have an __m128i key 
cdef __m128i v 
cdef char* array = python_bytes_array # auto conversion 
cdef int i, j 

# you NEED to ensure that the byte array has a length divisible by 
# 16, otherwise you'll probably get a segmentation fault. 
for i in range(0,len(python_bytes_array),16): 
    # go over in chunks of 16 
    v = _mm_set_epi8(array[i+15],array[i+14],array[i+13], 
      # etc... fill in the rest 
      array[i+1], array[i]) 

    cdef __m128 result = _mm_aesdec_si128(v,key) 

    # write back to the same place? 
    for j in range(16): 
     array[i+j] = _mm_extract_epi8(result,j) 
+0

可以產生一個循環,在每次迭代中沒有一堆函數調用開銷的情況下對數組進行解碼?如果沒有,您可能需要編寫編碼/解碼C函數。 –

+0

是的 - 我相信。 Cython可以生成C代碼,它可以遍歷數組並調用C函數,速度與C相當。(當C編譯器看到這些「函數調用」時,它應該直接將它們轉換爲單個處理器指令(希望!),而不是實際上做一個函數調用)。 – DavidW

+0

看起來太棒了。現在我該如何將它應用於字節(Python 3)對象? – ArekBulski