Cython创建并使用二维数组

因为cython无法使用形如int[8][9]这样的语句直接创建二维数组,因此我们另辟蹊径,使用malloc遍历x维度,手动分配内存空间

pyx文件

# cython: language_level=3
#cython_2darr.pyx
#fumiama 20201225
from libc.string cimport memcpy, memset
from libc.stdlib cimport malloc, free
cdef int** arr
def set(x: int, y: int, item: int):
    global arr
    arr[x][y] = item
def get(x: int, y: int):
    global arr
    return arr[x][y]
def createArray(x: int, y: int):
    global arr
    arr = <int**>malloc(x * sizeof(int*))
    for i in range(x):
        arr[i] = <int*>malloc(y * sizeof(int))
        memset(arr[i], 0, y * sizeof(int))

setup文件

# cython: language_level=3
#cython_2darr_setup.py
#fumiama 20201225
from distutils.core import setup
from Cython.Build import cythonize
setup(
    ext_modules = cythonize("cython_2darr.pyx")
)

编译

$ python3 ./cython_2darr_setup.py build_ext --inplace
Compiling cython_2darr.pyx because it changed.
[1/1] Cythonizing cython_2darr.pyx
running build_ext
building 'cython_2darr' extension
clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk -I/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -I/usr/local/include -I/usr/local/opt/[email protected]/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/[email protected]/3.8.5/Frameworks/Python.framework/Versions/3.8/include/python3.8 -c cython_2darr.c -o build/temp.macosx-10.14-x86_64-3.8/cython_2darr.o
clang -bundle -undefined dynamic_lookup -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk build/temp.macosx-10.14-x86_64-3.8/cython_2darr.o -L/usr/local/lib -L/usr/local/opt/[email protected]/lib -L/usr/local/opt/sqlite/lib -o ./cython_2darr.cpython-38-darwin.so

测试

$ python3
Python 3.8.5 (default, Jul 21 2020, 10:42:08) 
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cython_2darr
>>> cython_2darr.createArray(1000,1000)
>>> cython_2darr.get(0,0)
0
>>> cython_2darr.set(0,0,114514)
>>> cython_2darr.get(0,0)
114514
>>> exit()

猜你喜欢

转载自blog.csdn.net/u011570312/article/details/111703207
今日推荐