python - 使用 python 驱动程序将数据传入和传出 C++ 代码

标签 python c++ floating-point ctypes

我正在尝试将数组从 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?

您使用的是整数除法而不是 float 除法。

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

result[i] = i / 10.;

代替:

result[i] = i / 10;

关于python - 使用 python 驱动程序将数据传入和传出 C++ 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39380723/

相关文章:

algorithm - 卡汉求和

java - 为什么多次加0.1仍然无损?

python - 如何将带有附加功能的 Python 模块打包为默认值?

python - Django 中的全局小数舍入选项

c++ - MPI_Send + struct + 动态内存分配

c++ - makefile 有问题,没有引用资料

c - IEEE 754 表示

Python:在多个线程中从同一个列表迭代器中获取值是否安全?

python - 如何使用python在JSON中添加父对象

c++ - 在标准中,例如 `std::function<int(char)>`中定义的模板参数的语法是什么?