Bartek
Bartek

Reputation: 169

Delphi application fails to call a simple C++ DLL function

I would like to write a C++ DLL and call it from Delphi 6 application. I started with simple HelloWorld code from a tutorial and even though it works very well when called from a C++ program, in Delphi app it results in following error message Error in Delphi 6 application

MyDll.h

#ifndef _MY_DLL_H_
#define _MY_DLL_H_

#if defined MY_DLL
#define MYDLL_API __declspec(dllexport)
#else
#define MYDLL_API __declspec(dllimport)
#endif

extern "C"
{
    MYDLL_API int HelloWorld();
}
#endif

MyDll.cpp

#define MY_DLL

#include <windows.h>
#include "MyDll.h"

BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
        case DLL_PROCESS_ATTACH:
        case DLL_THREAD_ATTACH:
        case DLL_THREAD_DETACH:
        case DLL_PROCESS_DETACH:
            break;
    }
    return TRUE;
}

MYDLL_API int HelloWorld()
{
    return 9;
}

This Delphi code fails to call the DLL

function HelloWorld(): LongInt; cdecl; external 'MyDll.dll' name 'HelloWorld';

While the following C++ code works correctly

#include <iostream>
#include <windows.h>

typedef int (*HelloWorldFunc)();

int main()
{
    HelloWorldFunc _HelloWorldFunc;
    HINSTANCE hInstLibrary = LoadLibrary("MyDLL.dll");

    if (hInstLibrary)
    {
        _HelloWorldFunc = (HelloWorldFunc)GetProcAddress(hInstLibrary, "HelloWorld");
        if (_HelloWorldFunc)
        {
            std::cout << "HelloWorld result is " << _HelloWorldFunc() << std::endl;
        }
        FreeLibrary(hInstLibrary);
    }
    else
    {
        std::cout << "DLL Failed To Load!" << std::endl;
    }
    std::cin.get();
    return 0;
}

Upvotes: 4

Views: 602

Answers (1)

David Heffernan
David Heffernan

Reputation: 612794

The error is produced by the loader as it attempts to load the executable and resolve its dependencies. The error means that the loader failed to do this.

The error code is an NTSTATUS code, namely STATUS_INVALID_IMAGE_FORMAT. That is almost always due to a bitness mismatch. A 32-bit host loading a 64-bit DLL, or vice versa.

Given that Delphi 7 is a 32-bit compiler, it would seem likely that your C++ compiler is a 64-bit compiler. You will need to compile the C++ code with a 32-bit compiler in order to consume it from your 32-bit Delphi code.

Upvotes: 4

Related Questions