对于 TMemoryStream->WriteBuffer (C++Builder XE7),将 int 转换为 void* 并将 void* 转换为 int

Cast int to void* and void* to int for TMemoryStream->WriteBuffer (C++Builder XE7)

我使用 TMemoryStream class 及其 WriteBuffer 方法将数据写入流。我需要写入和读取 int 变量。

void __fastcall WriteBuffer(const void *Buffer, int Count)
void __fastcall ReadBuffer(void *Buffer, int Count)

下面的代码是否正确?

写作:

int i = 5;
stream->WriteBuffer((void*)&i, sizeof(int));

阅读:

stream->ReadBuffer((void*)&i, sizeof(int));

Is following code correct or no?

是的。虽然类型转换不是必需的,因为任何指针都可以传递给 void*(当然要考虑 const 的正确性):

int i = 5;
stream->WriteBuffer(&i, sizeof(int));

int i;
stream->ReadBuffer(&i, sizeof(int));