Why does Powerbasic crash when calling a (Purebasic ?) DLL?

Started by Theo Gottwald, September 12, 2023, 12:11:42 PM

Previous topic - Next topic

0 Members and 7 Guests are viewing this topic.

Theo Gottwald

To day I had the case that a Subprogram from a DLL (made in Purebasic)
was wrongly declared on the Powerbasic Side.

The declaration missed 1 Parameter (that was added later).

Was before:
DECLARE FUNCTION ELabs_GetMP3_TTS LIB "U1.DLL" ALIAS "ELabs_GetMP3_TTS" (BYVAL TEXT AS WSTRING, BYVAL mp3_fn AS WSTRING) AS LONG 


Should be:
DECLARE FUNCTION ELabs_GetMP3_TTS LIB "U1.DLL" ALIAS "ELabs_GetMP3_TTS" (BYVAL TEXT AS WSTRING, BYVAL mp3_fn AS WSTRING, OPTIONAL BYVAL modeln AS LONG) AS LONG 

Result:
The Powerbasic Program crashed after it reached the "EXIT SUB".
It never returned from that Sub.

So if you have the case that a Powerbasic SUB does not continue to run after
you call external DLL Functions, check your Declarations.
 
The problem has to do with the fact that Parameters as well as the return address from SUB's are placed on the stack. If things do not match perfectly this is what happens.

Charles Pegge

With the STDCALL calling convention the called function adds the assumed parameter space allocation  to the stack pointer when it returns. Adding to the stack pointer is how local space is dis-allocated.

Unused OPTIONAL parameters always push a value onto the stack, a null when unspecified by the caller.

So in this case, without the optional parameter,  the caller loses the last 4 bytes of its local space after making the call.

Theo Gottwald

Its like with the human Brain, Computers can not check their integrity on this level.

Charles Pegge

With CDECL and MS64, and all variadic calls, the caller performs the stack dis-allocation. It's a bit more error tolerant, and easier to trace errors.