Page 1 of 1

Invalid class typecast error in a dll

Posted: Fri 09 Dec 2011 11:45
by halmo
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:

Posted: Fri 09 Dec 2011 16:27
by AndreyZ
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.

Posted: Fri 09 Dec 2011 20:26
by halmo
:D
That solvesd my problem.
Thank you!!!!!!!

Posted: Mon 12 Dec 2011 16:53
by AndreyZ
If any other questions come up, please contact us.