by Richard Russell, March 2015
Passing a string as an input parameter to a DLL function is straightforward, but if the parameter is intended to receive a string output by the function then there are two important requirements:
For example suppose you want to call the GetComputerName API. MSDN states that the maximum length of the returned string is MAX_COMPUTERNAME_LENGTH characters so the required code is as follows:
MAX_COMPUTERNAME_LENGTH = 15 computer$ = STRING$(MAX_COMPUTERNAME_LENGTH + 1, CHR$0) size% = LEN(computer$) SYS "GetComputerName", computer$, ^size% computer$ = LEFT$(computer$, size%) PRINT computer$
Note particularly the initialisation of the string computer$ to be long enough to contain the maximum length of returned string, and to have an explicit NUL termination.
Here is another example, the conversion of a string from UTF-8 encoding to UTF-16 encoding. This time the maximum length of the returned string isn't known in advance, so it is first necessary to find out what that length is in order to initialise the string to a sufficient length:
CP_UTF8 = &FDE9 utf8$ = "демонстрация" SYS "MultiByteToWideChar", CP_UTF8, 0, utf8$, -1, 0, 0 TO size% utf16$ = STRING$(2*size% + 1, CHR$0) SYS "MultiByteToWideChar", CP_UTF8, 0, utf8$, -1, utf16$, size% TO ret% utf16$ = LEFT$(utf16$, 2*ret%)
Note the multiplications-by-2 to take account of the fact that UTF-16 strings require two bytes per character.