connecting and using a Delphi DLL in C++ Builder

2.1k views Asked by At

I wanted to ask for some help. I know, that there are a lot of places, where i can get this information. But, anyway, I have a problem connecting a Delphi DLL to my C++ Builder project.

For example, my Delphi DLL looks like:

library f_dll;

uses
  SysUtils,
  Classes,
  Forms,
  Windows;

procedure HW(AForm : TForm);
        begin
                MessageBox(AForm.Handle, 'DLL message', 'you made it!',MB_OK);
        end;
exports
        HW;

{$R *.res}

begin

end.

And this is how i connect a DLL and a function inside:

//defining a function pointer type
typedef void (*dll_func)(TForm* AForm);

dll_func HLLWRLD = NULL;

HMODULE hDLL = LoadLibrary("f_dll.dll");
if (!hDLL) ShowMessage("Unable to load the library!");

//getting adress of the function
HLLWRD = (dll_func)GetProcAddress(hDLL, "_HW"); 

if (!pShowSum) ShowMessage("Unable to find the function");

HLLWRLD(Form1);

FreeLibrary(hDLL);

I have no mistake messages from compiler, I only have my Message Box saying, that dll is not connected. I have put my dll in project folder, in Debug folder. but there is just no connection.

Please, I am asking you to help me. What is my mistake?

EDIT: i've posted C++ code with mistakes, so here is the right one (this is for people, that have similar problems):

//defining a function pointer type
typedef void (*dll_func)(TForm* AForm);

dll_func HLLWRLD = NULL;

HMODULE hDLL = LoadLibrary("f_dll.dll");
if (!hDLL) ShowMessage("Unable to load the library!");

//getting adress of the function
HLLWRD = (dll_func)GetProcAddress(hDLL, "HW");  //HW instead _HW

if (!HLLWRLD) ShowMessage("Unable to find the function"); //HLLWRLD instead pShowSum

HLLWRLD(Form1);

FreeLibrary(hDLL);
1

There are 1 answers

2
David Heffernan On BEST ANSWER
  1. If the DLL is in the same directory as the executable it will be found.
  2. The name exported by the Delphi DLL is HW rather than _HW.
  3. The calling conventions likely do not match. It's register in Delphi and cdecl in C++ I suspect. Note that I'm not 100% sure C++ Builder defaults to cdecl here, you can check.

The more serious problem is that you simply cannot pass a TForm across a DLL boundary like this. When you call a method on the object in your DLL you are calling code in the DLL rather than code in the host exe. But it's the code in the exe that you need to be called since that's the code that belongs with the object.

You need to switch to runtime packages or interfaces.