再會,
我是 Python 中的 C 和 ctypes 的新手。
我正在嘗試將 C 函式傳遞到 Python 代碼中。
在以下 C 函式中讀取二維陣列(形狀為 10,000 x 521 的“St”和形狀為 10,000 x 520 的“dZ”)時,我不斷收到以下錯誤:“訪問沖突讀取 0x0...”:
#include <math.h>
#include <stdio.h>
double change (double * dZ, double * St, size_t lenTaus, size_t lenSims)
{
size_t i, j;
double a, b;
for (i = 0; i < lenSims; i ) /*Iterate through simulations.*/
{
for (j = 0; j < (lenTaus - 1); j ) /*Iterate through taus.*/
{
a = St[lenTaus * i j];
b = dZ[lenTaus * i j];
}
}
return 0.0;
}
變數“lenSims”和“lenTaus”分別為 10,000 和 521。
呼叫C函式的Python代碼是:
import ctypes
impor t numpy as np
cCode = ctypes.CDLL("cCode_e.so") ### Read the C code in a form of shared library.
cCode.change.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.c_size_t, ctypes.c_size_t] ### Let know what kind of input we provide to the C function.
cCode.change.restype = ctypes.c_double ### Let know what kind of output we expect from the C function.
St_Python = np.zeros([10000,521])
dZ_Python = np.random.randn(10000,520)
St = St_Python.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) ### Convert a numpy array into a pointer to an array of doubles.
dZ = dZ_Python.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) ### Convert a numpy array into a pointer to an array of doubles.
lenTaus = St_Python.shape[1] ### Find the number of columns in the original array.
lenSims = St_Python.shape[0] ### Find the number of rows in the original array.
out = cCode.change(dZ, St, lenTaus, lenSims) ### Call the C function
如果我正確理解了問題,那么在將整個陣列作為指向 C 函式的指標傳遞時,我會錯誤地使用記憶體。但我不知道如何以正確的方式傳遞它們。
我可以請你幫忙嗎?
此致,
葉夫根尼
uj5u.com熱心網友回復:
看起來問題是由緩沖區溢位引起的。
假設陣列定義為:
St_Python = np.zeros([10000,521])
dZ_Python = np.random.randn(10000,520)
在C函式的引數lenTaus和LenSims是521和10000分別。結果,dZ訪問的最終偏移量是:
lenTaus * i j = lenTaus * (lenSims-1) (lenTaus - 1 - 1)
= 521*9999 521-1-1
= 5209998
的大小dz是10000 * 520什么5200000是小于最終的偏移因而存在一個緩沖區溢位和未定義行為被呼叫。
解決方案之一是將偏移計算更改為dZ:
b = dZ[(lenTaus - 1) * i j];
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/365831.html
