[fpc-pascal] Stack alignmennt in call from C++ to FPC

Josue Andrade Gomes josuegomes at gmail.com
Wed Jun 5 15:04:58 CEST 2013


Stack alignmennt in call from C++ to FPC

Hi,

I have recently ported a Delphi application to Lazarus/FPC (Win32/x86).
This application makes use of a DLL implemented in MS Visual C++ 2010.

The calls from FPC code to C++ code work fine. However this DLL also
has a callback
system for notifications. When the DLL calls a FPC callback function
a crash occurs inside the DLL with a 'Datatype misalignment' exception (1).

Some references (eg (2)) claim that MSVC aligns the stack at 4-byte
boundaries while GCC aligns
at 16-byte boundaries. I have found no confirmation on those claims.

With GCC I could use __attribute__((force_align_arg_pointer)) in the
callback declaration.
Or even -mstackrealign. However I can't find a similar option with FPC.

Any idea?

Thanks for any help.

Here some code excerpts:

{ FPC }
type
 TMyCallback = procedure(s : PChar); stdcall;
...
procedure RegisterCallBack(callback: TMyCallback); stdcall; external
'MyDll.dll';
...
procedure Callback(s : PChar); stdcall;
begin
{ use s }
end;
...
RegisterCallBack(Callback);
...

// C++
typedef void (__stdcall *Callback_t)(const char* s);
extern "C" {
__declspec(dllexport) void RegisterCallback(Callback_t p);
}

...

static Callback_t callback = 0;

void RegisterCallback(Callback_t p)
{
callback(p);
}
...
// at some point the callback is called;
if (callback)
callback("hello world"); // <== crashes here


--
Josue A. Gomes
josuegomes.com


(1) Actual error: Unhandled exception at 0x00411990 in Project1.exe:
0x80000002: Datatype misalignment.
(2) http://www.gamedev.net/topic/482230-mingw-dll-used-in-mingw-and-vc-app-memory-alignment/



More information about the fpc-pascal mailing list