gpt4 book ai didi

c++ - 将自定义数据类型输出到文件

转载 作者:行者123 更新时间:2023-11-28 06:55:34 25 4
gpt4 key购买 nike

给定结构 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 最终读取 (4*sizeof(float) - sizeof(Pixel))*10 = 40 超出 pixels 数组末尾的字节。这在文件内容中显示为 10 (40/4) 个额外的随机值。

关于c++ - 将自定义数据类型输出到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23231691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com