gpt4 book ai didi

python - 当 numpy 数组被 C 函数改变时,魔法就发生了

转载 作者:行者123 更新时间:2023-11-30 14:59:04 25 4
gpt4 key购买 nike

我正在尝试将 numpy 数组传递到我想要更改数组值的 C 函数中。但我必须将索引乘以 2 才能使其正常工作。将值分配给奇数索引(假设为i)会导致将垃圾分配给索引(i-1)/2。这是源代码。

C:

#include "assign_array.h"

void assign(int *arr, int i) {
arr[i] = 2017;
}

Python:

import ctypes, numpy
lib2 = ctypes.cdll.LoadLibrary('./assign_array.so')
for i in range(5):
array = numpy.zeros(8, dtype = int)
ptr = array.ctypes.data_as(ctypes.POINTER(ctypes.c_int))
print('i = {}:'.format(i))
lib2.assign(ptr, i)
print(array)

Screenshot

为什么会发生这种情况?

最佳答案

这不完全是垃圾:20470x7e186629490360320x7E100000000 >。看起来好像您正在混合不同的 C 编译器(或提供给 C 编译器的标志),因此 Python 认为 int 是 64 位,但您的 C 编译器认为 int是32位的。但实际上,Python 中的 int 并不保证与 C 编译器中的 int 匹配;它可能更典型地匹配long

根据the numpy documentationdtype 可以指定为 numpy.int32 以特指 32 位 int。这可能是处理此问题的最简单方法,或者当然您可以更改 C 代码以使用 long(假设 C 编译器设置中为 64 位 long) .

关于python - 当 numpy 数组被 C 函数改变时,魔法就发生了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43023462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com