Page 1 of 1

Invalid class typecast inside DLL (5.80.0.47)

Posted: Thu 22 Jul 2010 04:52
by maciejmt
Hello !.
I have problem.
From main application, I try share connection to DB with my DLL.
DLL correctly shows database, username, password, server, but if I open Query then is throwing exception :(

if, Instead of TMyConnection, I put TMyQuery as result of "GetConnection" and directly use, then is OK...

Code: Select all

library Project1;

uses
  MyAccess, Dialogs;

{$R *.res}

type
  ILabReport = interface
    ['{868368F0-42D9-404E-960A-EF3EEFFE87CF}']
    procedure CreateReport(const Path: PChar);
  end;

  ILabProgram = interface
    ['{B3E9CEF9-E3FF-4A77-A61E-3B8942BF7D41}']
    function GetConnection: TMyConnection;
  end;

  TLabReport = class(TInterfacedObject, ILabReport)
    private
      Q: TMyQuery;
    public
      constructor New;
      procedure CreateReport(const Path: PWideChar);
  end;

var
  LabReport: ILabReport;
  LabProgram: ILabProgram;


procedure TLabReport.CreateReport(const Path: PWideChar);
begin
  Q.Connection := LabProgram.GetConnection;

  Q.SQL.Text := 'SELECT xx from xxxx';
  Q.Open;
  showmessage(Q.Fields[0].AsString);
  Q.Close;
end;

constructor TLabReport.New;
begin
  Q := TMyQuery.Create(nil);
end;

procedure Connect(const LabProg: ILabProgram; out LabRep: ILabReport);
begin
  LabProgram := LabProg;
  LabReport := TLabReport.New;
  LabRep := LabReport;
end;

procedure Disconnect;
begin
  LabReport := nil;
  LabProgram := nil;
end;

exports
  Connect, Disconnect;


begin
end.

Posted: Thu 22 Jul 2010 13:14
by maciejmt
OK, I create TMyConnection and Assigned connection from App. It is only way (without create TMyConnection)?

Code: Select all

procedure TLabReport.CreateReport(const Path: PWideChar);
var
  c: tmyconnection;
begin
  c := tmyconnection.Create(nil);
  c.AssignConnect(LabProgram.GetConnection);
  Q.Connection := c;//LabProgram.GetConnection;

  Q.SQL.Text := 'SELECT x from xxx';
  Q.Open;
  showmessage(Q.Fields[0].AsString);
  Q.Close;
end;

Posted: Thu 22 Jul 2010 15:35
by Dimon
This problem is connected with work with dll. The point is that you create the TMyConnection class object in an application and use it with the TMyQuery object, created in dll. These methods use the "as" operator which returns invalid type cast error.
To solve the problem you can use the TCustomMyConnection.AssignConnect method to assign the TMyConnection object created in application to the TMyConnection object of dll. Or you can just create TMyConnection object in dll.
Also you can use the approach used in the MyDAC DLL demo. You can find this demo by the following path: MyDAC_InstDir\Demos\Miscellaneous\Dll.
MyDAC_InstDir is the MyDAC installation directory on your computer.