簡體   English   中英

如何將浮點 2d numpy 數組傳遞給 c?

[英]How to pass a float 2d numpy array to c?

我想使用 C 來加快計算速度。

我已經閱讀了以下信息:

如何將二維數組從 Python 傳遞到 C?

我想將浮點 2d numpy 數組傳遞給 c。

c 代碼如下

#include <stdio.h>

double main(double **fp2)
{
    int i;
    for ( i=0; i < 10; i++ )
        printf("%d, %d\n", fp2[i][0], fp2[i][1]);

}

python 代碼如下

import ctypes
import os
import sys
cwd = os.path.dirname(os.path.realpath(__file__))
#
import numpy as np


DLL_NAME = "./simple_print.{:s}".format("dll" if sys.platform[:3].lower() == "win" else "so")

C_double_Ptr = ctypes.POINTER(ctypes.c_double)
C_double_PtrPtr = ctypes.POINTER(C_double_Ptr)

my = ctypes.CDLL(DLL_NAME)
myFunc = my.main
myFunc.argtypes = [C_double_PtrPtr]
myFunc.restype = ctypes.c_double

np_array_2d = np.array(np.random.rand(10,2), dtype=np.float64)

print(np_array_2d)


ct_arr = np.ctypeslib.as_ctypes(np_array_2d)
C_double_PtrArr = C_double_Ptr * ct_arr._length_
ct_ptr = ctypes.cast(C_double_PtrArr(*(ctypes.cast(row, C_double_Ptr) for row in ct_arr)), C_double_PtrPtr)
res = myFunc(ct_ptr)



print("\n{0:s} returned: {1:f}".format(myFunc.__name__, res))

但是 python 和 C 之間的結果不同。

python
[[0.66088702 0.95406219]
 [0.18609616 0.89634064]
 [0.0174235  0.52141446]
 [0.4939825  0.67305432]
 [0.45147721 0.13951316]
 [0.16937601 0.57228122]
 [0.57805704 0.98001207]
 [0.99983335 0.63249494]
 [0.51295051 0.08450172]
 [0.20974118 0.7960613 ]]
C
-1960361805, 1835376087
-1248799216, -1885421307
1842847712, 1615298041
-940448502, 903669117
-1443205772, 1053507048
-190023196, -1244975300
2034696801, 1139364725
-2064136264, 161766169
766548286, -1425458880
-2106453208, -1975869746

main returned: 0.000000

請幫我...

您在 c 中打印時所做的是一次使用自定義格式的兩個浮點數。

在 python 中,您使用了數組和浮點數的默認打印方法。

然后主要的變化是你在 c 中打印了 integer:

這是因為您使用了 %d (表示整數)而不是 %f (表示浮點數)。

假設您的 python 和 c 代碼工作正常。

您需要更改其中之一:

如果選擇更改 python:

代替:

print(np_array_2d)

和:

    for f, s in np_array_2d:
        print(f, s, sep=", ")

如果您選擇更改 c 代碼:

double main(double **fp2) {
    int i;
    printf("[");
    for ( i=0; i < 10; i++ )
        printf("[%f, %f]\n", fp2[i][0], fp2[i][1]);
    printf("]");
}

無論如何,您都需要將 %d 更改為 %f

我還強烈建議更改 c 函數的名稱,這一次可能不會有問題,但在很多情況下可能會出現問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM