Changing Help about Returning Strings from Dll

Got an idea for enhancing PureBasic? New command(s) you'd like to see?
Konne
Enthusiast
Enthusiast
Posts: 434
Joined: Thu May 12, 2005 9:15 pm

Changing Help about Returning Strings from Dll

Post by Konne »


Note about returning strings from DLL's:

If you want to return a string out of a DLL, the string has to be declared as Global before using it.

Example:

Global ReturnString$

ProcedureDLL.s MyFunction(var.s)
ReturnString$ = var + " test"
ProcedureReturn ReturnString$
EndProcedure

Without declaring it as Global first, the string is local to the ProcedureDLL and cant be accessed from outside.

When using CallFunction() (or one of its similar CallXXX functions) on a DLL function you will get a pointer on the return string, which you could read with PeekS().

Example:

String.s = PeekS(CallFunction(0,"FunctionName",Parameter1,Parameter2))
This recommendation of handling strings should be removed or there should be a clue that this is NOT THREADSAFE.

Instead of that you should pass a Pointer to a Buffer and the Len of the Buffer to the DLL Procedure and the Procedure should return if the Buffer is long enough to hold the String.

For example:

Code: Select all


ProcedureDLL Dll(*Pointer,StringLen.l)
  ReturnString.s="This is a Test"
  
  If StringByteLength(ReturnString)+SizeOf(Character)<=StringLen
    PokeS(*Pointer,ReturnString)
    ProcedureReturn 1
  Else
    ProcedureReturn 0  
  EndIf
EndProcedure

#Memory=255

String.s{#Memory}

If Dll(@String,#Memory*SizeOf(Character))
  Debug String
Else
  Debug "String is too long"
EndIf

#Memory2=10

String2.s{#Memory2}

If Dll(@String2,#Memory2*SizeOf(Character))
  Debug String2
Else
  Debug "String to copy is too long"
EndIf
Apart from that Mrs Lincoln, how was the show?