使用 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]

I know the data is passing to the code correctly, but seems to be truncating on the way back. I'm losing my precision after the decimal. Any ideas where I went wrong?

您正在使用整数除法而不是浮点除法。

您可以使用以下方法解决此问题:

result[i] = i / 10.;

而不是:

result[i] = i / 10;