Programming C++Builder Exception class EInvalidCast with message 'Invalid class typecast' in Delphi/C++Builder programs
Notice: Undefined variable: relatedArticlesCount in /home/wwwroot/codeback.net/plugins/content/tags.php on line 149

Project aaa.exe raised exception class EInvalidCast with message 'Invalid class typecast'. Process stopped. Use Step or Run to continue. This is the error message prompt by delphi or c++builder enviroment when debugging the program. This is always caused by the incorrect typecast.

Let us see an example attached by c++builder to show how to read the data from a memo field into a blob stream and display it in a memo control. To run this program, do not use a BDE data engine to connect to the database.

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    int MemSize;
    char *Buffer;
    TBlobStream *Stream;
    if (!Query1->Eof)
    Query1->Next();

    //Error message would raise on the following code line.
    Stream = new TBlobStream((TBlobField *)Query1->FieldByName("Notes"), bmRead);

    try
    {
        MemSize = Stream->Size + 1; // add one for null terminator
        Buffer = new char[MemSize]; // Allocate the memory.
        try
        {
            Stream->Read(Buffer, MemSize); //Read Notes field into buffer.
            Memo1->SetTextBuf(Buffer);  // Display the buffer's contents.
        }
        catch (...)
        {
            delete Buffer;
            throw;
        }
        delete Buffer;
    }
    catch (...)
    {
        delete Stream;
        throw;
    }
    delete Stream;
}

The error message mention above would raise on this line: Stream = new TBlobStream((TBlobField *)Query1->FieldByName("Notes"), bmRead);

When you use a BDE data engine to connect to the database, the error would not raised, because TBlobStream was designed to use for the BDE data engine. When we use an ADO or other data engine to connect to the database, we should use the proper component to access to the blob field.

If we use the ado, we should use a TADOBlobStream, while use the clientdataset, we should use a TClientBlobStream replace. For detail, see the article here.

Also, to avoid this error raise, we could use a common statement: "CreateBlobStream". This is the case: 
    TStream *Stream   =   ADOQuery1->CreateBlobStream((TBlobField *)Query1->FieldByName("Notes"),  bmReadWrite);


Add comment


Security code
Refresh

Programming - C++Builder