C ++ Builder将TMemoryStream缓冲区读取为void指针

时间:2015-08-19 17:57:06

标签: c++ pointers c++builder

我正在尝试将TMemoryStream缓冲区的内容复制到void指针,下面你可以看到不起作用的示例代码 - void buffer为空,但textbox包含有效大小 - 我用winrar大小检查它。以下代码创建了exe文件,但它的大小为0。

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    TMemoryStream* ms = new TMemoryStream();
    Download->Get("http://rarlab.com/rar/wrar521pl.exe",ms);
    this->Edit1->Text = ms->Size;
    void* buffer = malloc(ms->Size );
    ms->Read(buffer,ms->Size);
    FILE* pFile = fopen("test.exe","wb");
    fwrite(buffer,4,ms->Size,pFile);
    fclose(pFile);
    delete ms;
}

另外,我知道我可以轻松地将TMemoryStream缓冲区的内容保存到文件中,但我需要将其内容作为void指针,所以我编写了以下代码来测试它。

1 个答案:

答案 0 :(得分:1)

从流中读取的代码几乎正确。在读取之前,您没有将流的Position属性重置为0,因此您实际上是在流的末尾读取,其中没有要读取的数据。

试试这个:

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    TMemoryStream* ms = new TMemoryStream();
    try
    {
        Download->Get("http://rarlab.com/rar/wrar521pl.exe", ms);
        ms->Position = 0; // <-- ADD THIS
        Edit1->Text = ms->Size;
        void* buffer = malloc(ms->Size);
        if (buffer)
        {
            ms->ReadBuffer(buffer, ms->Size);
            // ms->SaveToFile("test.exe");
            FILE* pFile = fopen("test.exe", "wb");
            if (pFile)
            {
                fwrite(buffer, 1, ms->Size, pFile);
                fclose(pFile);
            }
            free(buffer);
        }
    }
    __finally
    {
        delete ms;
    }
}

或者,只是不分配单独的缓冲区,而是直接使用流的自己的缓冲区:

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    TMemoryStream* ms = new TMemoryStream();
    try
    {
        Download->Get("http://rarlab.com/rar/wrar521pl.exe", ms);
        Edit1->Text = ms->Size;
        void* buffer = ms->Memory;
        // ms->SaveToFile("test.exe");
        FILE* pFile = fopen("test.exe", "wb");
        if (pFile)
        {
            fwrite(buffer, 1, ms->Size, pFile);
            fclose(pFile);
        }
    }
    __finally
    {
        delete ms;
    }
}