How do I export function from C++ DLL and use in delphi?

c++, delphi, dll

Solution

You can export it as a C function (`__cdecl`), so that it has a nice name on the exports table.

Name-decoration convention: Underscore character (_) is prefixed to names, except when exporting __cdecl functions that use C linkage.

So basically, your function will have the name `xMain` in the exports table.

extern "C" __declspec(dllexport) void xMain()

And in the Delphi part, you just specify `cdecl` and call it normally:

var
  xMainPrc: procedure; cdecl;

For example:

if @xMainPrc <> nil then
begin
  MessageBox(0,'Function Loaded', 0, 0);
  xMainPrc;
end;

Problem

I am trying to create a DLL in C++ and export a function. This is my C++ code: ``` #include <Windows.h> void DLLMain(){ } __declspec(dllexport) void xMain(){ MessageBox(NULL,L"Test",L"Test",NULL); } ``` This is my delphi code: ``` program prjTestDllMain; Uses Windows; Var xMainPrc:procedure;stdcall; handle : THandle; begin handle := LoadLibrary('xdll.dll'); if handle <> 0 then begin MessageBox(0,'DLL Loaded', 0, 0); @xMainPrc := GetProcAddress(handle, 'xMain'); if @xMainPrc <> nil then MessageBox(0,'Function Loaded', 0, 0) else MessageBox(0,'Function Not Loaded', 0, 0); MessageBox(0,'Process End', 0, 0); FreeLibrary(handle); end else MessageBox(0,'DLL Not Loaded', 0, 0); end. ``` I get a messagebox for "DLL Loaded" just fine. But I get "Function Not Loaded" afterwards. What am I doing wrong here?

Original source