Invalid class typecast error in a dll

Discussion of open issues, suggestions and bugs regarding MyDAC (Data Access Components for MySQL) for Delphi, C++Builder, Lazarus (and FPC)
Post Reply
halmo
Posts: 9
Joined: Mon 09 Jul 2007 10:27

Invalid class typecast error in a dll

Post by halmo » Fri 09 Dec 2011 11:45

Hi guys!

I made a test application:

Dll code:

Code: Select all

library dlltest;

uses
  SysUtils,
  Classes,
  MyAccess;

procedure Test(MyConnection: TMyConnection); cdecl; export;
var q: TMyQuery;
begin
  try
    q:=TMyQuery.Create(nil);
    q.Connection:=MyConnection;
    q.SQL.Text:='select version() as ver';
    q.Open;    //  <--- Here is the error: Invalid class typecast
    q.Close;
  except
  end;
  FreeAndNil(q);
end;

exports
  Test;

begin
end.

and the caller code:

Code: Select all

program dllcaller;

{$APPTYPE CONSOLE}

uses
 MyAccess;

procedure Test(MyConnection: TMyConnection); cdecl; external 'dlltest.dll' name 'Test';

var conn: TMyConnection;

begin
  try
    conn:=TMyConnection.Create(nil);
    conn.Server:='localhost';
    conn.Database:='mysql';
    conn.Port:=3306;
    conn.Username:='root';
    conn.Password:='root';
    conn.LoginPrompt:=False;
    conn.Open;
    Test(conn);
    conn.Close;
  except
  end;
end.

what is the wrong?
:cry: :cry:

AndreyZ

Post by AndreyZ » Fri 09 Dec 2011 16:27

Hello,

This problem is caused by using a connection that was created in an application inside dll. In this case the "as" operator is used that causes invalid type cast error. To solve the problem, you can use one of the following ways:
- create and configure TMyConnection inside dll;
- create TMyConnection inside dll and use the AssignConnect method to share database connection. Here is an example:

Code: Select all

library dlltest;

uses
  SysUtils,
  Classes,
  MyAccess;

procedure Test(MyConnection: TMyConnection); cdecl; export;
var
  con: TMyConnection;
  q: TMyQuery;
begin
  con := TMyConnection.Create(nil);
  q := TMyQuery.Create(nil);
  try
    con.AssignConnect(MyConnection);
    q.Connection := con;
    q.SQL.Text := 'select version() as ver';
    q.Open;
    q.Close;
  except
  end;
  FreeAndNil(q);
  FreeAndNil(con);
end;

exports
  Test;

begin
end.

halmo
Posts: 9
Joined: Mon 09 Jul 2007 10:27

Post by halmo » Fri 09 Dec 2011 20:26

:D
That solvesd my problem.
Thank you!!!!!!!

AndreyZ

Post by AndreyZ » Mon 12 Dec 2011 16:53

If any other questions come up, please contact us.

Post Reply