簡體   English   中英

使用python驅動程序在C ++代碼之間來回傳遞數據

[英]Passing data to and from C++ code using a python driver

我正在嘗試將數組從python驅動程序傳遞給c ++函數。 我傳遞給c ++函數的數組之一是結果數組。 我知道數據正確傳遞給了代碼,但似乎在返回的途中被截斷了。 小數點后的精度下降了。 有什么想法我做錯了嗎? 下面是該代碼的簡化版本以及結果輸出。

python代碼:

import ctypes
from ctypes import *

def get_calculate_windows():
    dll = ctypes.CDLL('./cppFunctions.so', mode=ctypes.RTLD_GLOBAL)
    func = dll.calculate_windows
    func.argtypes = [POINTER(c_float), POINTER(c_float), c_size_t]
    return func

def calculate_windows(data, answer, size):
    data_p = data.ctypes.data_as(POINTER(c_float))
    answer_p = answer.ctypes.data_as(POINTER(c_float))

    __calculate_windows(data_p, answer_p, size)


###### MAIN FUNCTION #####

data = np.array(myData, dtype=np.float32)
ans = np.array(myAnswer, dtype=np.float32)

print ans[:10]
calculate_windows(data, ans, myLength)
print ans[:10]

C ++代碼:

extern "C" {

    void calculate_windows(float *h_data, float *result, size_t size ) {

        for (int i=0; i<size; i++ ) {
            result[i]=i/10;
        }

    }
}

輸出:

[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]

輸出應為:

[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.0  0.1  0.2  0.3  0.4  0.5  0.6  0.7  0.8  0.9]

我知道數據正確傳遞給了代碼,但似乎在返回的途中被截斷了。 小數點后我失去了精度。 有什么想法我做錯了嗎?

您正在使用整數除法而不是浮點除法。

您可以使用以下方法解決此問題:

result[i] = i / 10.;

代替:

result[i] = i / 10;

暫無
暫無

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

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