user1769184 user1769184 - 1 month ago 16
C++ Question

ShowMessage not showing in Delphi DLL called from C++

I want to call this delphi code via a DLL from C++

procedure MyMessage; stdcall;
begin
ShowMessage(DLLName + ' more text');
end;


Using some delphi test code I see no problem , but from C++ no message box is shown.

i did the following C++ coding

// function prototype
typedef void(__stdcall*VoidCall)();

// prototype for info function inside DLL
extern "C" __declspec(dllimport) void __stdcall MyMessage();


MyMessage = (VoidCall)::GetProcAddress(load, "MyMessage");

MyMessage;


As I want to use as a next steps existing delphi forms with a wrapper DLL from C++ , I guess the solution of this problem will also enable me for the next task ....

Answer

The presented C++ code does not compile. It mixes binding of a dll via an import library with dynamic loading of a dll via LoadLibrary / GetProcAddress.

To load a DLL created with Delphi, it is easiest to use dynamic loading of the dll. Do this as follows:

//  function prototype 
typedef void(__stdcall*VoidCall)();

[...]

// Load the library
HMODULE lib = LoadLibrary("Project1.dll");
if (lib != 0)
{
    __try
    {
        // Get the address to the exported function in the DLL
        // and store it in the variable myMessageFunction
        VoidCall myMessageFunction = (VoidCall) GetProcAddress(lib, "MyMessage");

        // Call the function. Note you need the parenthesis even
        // when there are no parameters to pass
        myMessageFunction();
    }
    __finally
    {
        // Unload the library again. Note that you cannot use 
        // functions from the library after that. So only unload
        // the dll once you don't need it anymore.
        FreeLibrary(lib);
    }
}
else // TODO: Error handling, dll cannot be loaded

If you want to use load time linking, you can create a *.lib file to be used with C++ for a DLL created with Delphi. Use the solution from this question.