Cython创建并使用二维数组

14 篇文章 0 订阅

因为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/openssl@1.1/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python@3.8/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/openssl@1.1/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()
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值