正在将自定义数据类型输出到文件

Outputting custom data type to file

本文关键字:输出 文件 定义数据类型      更新时间:2023-10-16

给定一个结构Pixel及其等效MPI_Type mpiPixel,我创建一个像素数组并将其写入文件。除了文件中的输出以某种位模式(被解释为整数)结束之外,一切都运行正常。文件以二进制形式输出,因此为了查看它是否正确写入,我使用hexdump -v -e '7/4 "%10d "' -e '"n"' pixelsx

代码

struct Pixel
{
    int red; int green; int blue;
    Pixel() {}
    Pixel(int r, int g, int b)
    {
        red = r; green = g; blue = b;
    }
};

int main(int argc, char **argv)
{
    int rank, size;
    MPI_File   file;
    MPI_Offset offset;
    MPI_Status status;
    MPI_Datatype mpiPixel;
    Pixel pixels[10];
    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    /* fill local data */
    for (int i = 0; i < 10; i++)
        pixels[i] = Pixel(i, i, i);
    int blockcounts[1];
    MPI_Aint offsets[1];
    MPI_Datatype oldtypes[1];
    //Pixel Description {starting pos, element count, element type}
    offsets[0] = 0;
    blockcounts[0] = 3;
    oldtypes[0] = MPI_INT;
    /* Now define structured type and commit it */
    MPI_Type_struct(1, blockcounts, offsets, oldtypes, &mpiPixel);
    MPI_Type_commit(&mpiPixel);
    /* open the file, and set the view */
    MPI_File_open(MPI_COMM_WORLD, "pixels",
                  MPI_MODE_CREATE | MPI_MODE_WRONLY,
                  MPI_INFO_NULL, &file);
    MPI_File_seek(file, 0, MPI_SEEK_SET);
    MPI_File_set_view(file, 0,  MPI_CHAR, mpiPixel, "native", MPI_INFO_NULL);
    MPI_File_write_all(file, pixels, 10, mpiPixel, &status);
    MPI_File_close(&file);
    MPI_Finalize();
    return 0;
}

输出

     0          0          0          1          1          1          2
     2          2          3          3          3          4          4
     4          5          5          5          6          6          6
     7          7          7          8          8          8          9
     9          9    4228656          0          0          0    4228656
     0          0          0 -1795965243      32585   

不应该在那里的线路(如果我没有弄错的话)是

4228656          0          0          0    4228656         0          0          0 -1795965243      32585

为什么后者被打印在文件中。这是内存分配问题(数组?)?

附言:代码只使用一个进程运行。原因是我首先需要让写函数工作。然后添加其他进程的偏移量

MPI数据类型与C++结构完全不对应。您的Pixel结构由三个int元素组成。为四个float元素注册一个MPI数据类型,并使用它将结构数组写入文件。由于intfloat恰好在大多数32位和64位体系结构上具有相同的大小,并且由于在结构元素之间没有添加填充,MPI最终读取超过pixels阵列末尾的(4*sizeof(float) - sizeof(Pixel))*10 = 40字节。这在文件内容中显示为10(40/4)个附加随机值。