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
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;
}