Link to home
Start Free TrialLog in
Avatar of Stinne Høst
Stinne Høst

asked on

DLL written in Delphi cannot be loaded in C++

I have a dll written in Delphi that I need to call from a c++ program. My dll works when called from Delphi, both when using static and dynamic loading. However, in c++, LoadLibrary returns a null pointer. In both cases, test.dll is located in the same dir as the test program. I am a c++ beginner - any help is appreciated.

The dll:
library test;

uses
  System.SysUtils,
  System.Classes;

{$R *.res}
 function AddIntegers(_a, _b: integer): integer; stdcall;
begin
  Result := _a + _b;
end;

exports
  AddIntegers;

begin
end.

Open in new window


The Delphi test program - this return the line "3 + 4 is 7", as expected:
program SimpleDLLTest;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils, Winapi.Windows;

type
  TAddIntegersFunc = function (_a, _b: integer): integer; stdcall;
var
  DllHandle : HMODULE;
  AddIntegersFunc : TAddIntegersFunc;
  TestInt         : integer;
begin
  try
    DllHandle := LoadLibrary(pWideChar('test.dll'));
    if DllHandle = 0 then begin
      Writeln('Error loading dll');
    end else begin
      @AddIntegersFunc := GetProcAddress(DllHandle, 'AddIntegers');
      if assigned(AddIntegersFunc) then begin
        TestInt := AddIntegersFunc(3,4);
        Writeln('3 + 4 is ' + IntToStr(TestInt));
      end else begin
        Writeln('Function not found');
      end;
    end;
    Write('Press Enter'); ReadLn;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Open in new window


The c++ test program:
#include <windows.h>
#include <iostream>
using namespace std;

int main()
{
	HINSTANCE hGetProcIDDLL = LoadLibrary("test.dll");

	if (!hGetProcIDDLL)
	{
		cout<<"Could not load library!\n";
		cin.get();
	}
	else
	{
		cout<<"Library loaded!\n";
		cin.get();
	}

	return 0;
}

Open in new window


I did not write any function call in c++, since I have not yet even managed to load the library - I just get "Could not load library".
ASKER CERTIFIED SOLUTION
Avatar of Zoppo
Zoppo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Stinne Høst
Stinne Høst

ASKER

Hi Zoppo
The dll is located correctly, but the GetLastError helped - it was a 32 bit dll and a 64 bit program. Thanks a lot!!
Stinne
 it was a 32 bit dll and a 64 bit program

Open in new window


then, you have to convert either the one or the other.

i would recommend to get visual studio community 2017 (which is free) and then create a 64-bit dll project.

Sara
@Sara: I know I have to convert one or the other. I just hadn't realised that was the problem. Thanks for answering!