Interactive PowerBasic Forum

Purebasic-Tipps and Code => PureBasic Tipps and Tricks => Topic started by: Theo Gottwald on September 12, 2023, 12:11:42 PM

Title: Why does Powerbasic crash when calling a (Purebasic ?) DLL?
Post by: Theo Gottwald on September 12, 2023, 12:11:42 PM
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.
Title: Re: Why does Powerbasic crash when calling a (Purebasic ?) DLL?
Post by: Charles Pegge on September 12, 2023, 03:12:55 PM
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.
Title: Re: Why does Powerbasic crash when calling a (Purebasic ?) DLL?
Post by: Theo Gottwald on September 12, 2023, 10:05:09 PM
Its like with the human Brain, Computers can not check their integrity on this level.
Title: Re: Why does Powerbasic crash when calling a (Purebasic ?) DLL?
Post by: Charles Pegge on September 13, 2023, 11:08:57 AM
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.