设置数组元素时出现奇怪的结果C ++ / pybind11

问题描述

我正在尝试使用pybind11编写C ++扩展。该函数最终将以几个numpy数组作为输入,并返回几个numpy数组作为输出。 我一直在尝试直接传递目标numpy数组,并在C ++函数中就地更改值。

我正在测试以下代码

C ++

#include "pybind11/pybind11.h"
#include "pybind11/numpy.h"

namespace py = pybind11;

int nparraytest(py::array_t<float> A,py::array_t<float> B,py::array_t<float> C,py::array_t<float> D) {
    py::buffer_info Abuf = A.request();
    py::buffer_info Bbuf = B.request();
    py::buffer_info Cbuf = C.request();
    py::buffer_info Dbuf = D.request();

    int lxA = Abuf.shape[0];

    double* Aptr = (double*)Abuf.ptr;
    double* Bptr = (double*)Bbuf.ptr;
    double* Cptr = (double*)Cbuf.ptr;
    double* Dptr = (double*)Dbuf.ptr;

    for (int i = 0; i < lxA; i++) {
        int i30 = 3 * i;
        int i31 = i30 + 1;
        int i32 = i30 + 2;

        //optionA
        //Cptr[i30] = Aptr[i30];
        //Cptr[i31] = Aptr[i31];
        //Cptr[i32] = Aptr[i32];

        //Option B
        Cptr[i30] = Aptr[i30];
        Cptr[i31] = Aptr[i31];
        Cptr[i32] = Bptr[2];

        Dptr[i30] = Aptr[i30];
        Dptr[i31] = Aptr[i31];
        Dptr[i32] = Aptr[i32];
    }

    return lxA;
}

PYBIND11_MODULE(SeqRT,m) {
    m.def("nparraytest",&nparraytest,"Test");
}

python

import numpy as np
import SeqRT

if __name__ == '__main__':
    #initialize arrays
    A = np.arange(15,dtype = np.float32).reshape((5,3))
    B = np.arange(15,3))
    C = np.zeros((5,3),dtype = np.float32)
    D = np.zeros((5,dtype = np.float32)
    
    lxA = SeqRT.nparraytest(A,B,C,D)
    
    print(lxA)
    print(A)
    print(B)
    print(C)
    print(D)

现在,无论我使用选项A还是选项B中的代码,数组A,B和D以及数组C都总是按预期结束,即

[[ 0.  1.  2.]
 [ 3.  4.  5.]
 [ 6.  7.  8.]
 [ 9. 10. 11.]
 [12. 13. 14.]]

但是,使用选项B,我得到数组C的结果

[[ 0.  1.  2.]
 [ 3.  4.  5.]
 [ 6.  7.  8.]
 [ 9.  4.  5.]
 [12. 13. 14.]]

如您所见,值10和11.是不同的。实际上,使用其他输入作为数组B时,值4.和5.最终可能会非常随机。 相反,我希望这样:

[[ 0.  1.  2.]
 [ 3.  4.  2.]
 [ 6.  7.  2.]
 [ 9. 10.  2.]
 [12. 13.  2.]]

我不知道我的错误是什么

  • 是因为错误地使用了pybind / numpy数组吗?
  • 这是一般的C ++索引错误吗?
  • 此外,这种就地方法是否还不错?还是我应该创建两个缓冲口并将它们打包为元组以供返回?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)