User Tools

Site Tools


Calling DLL functions that return strings

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:

  • The string must be long enough to receive the returned data
  • The string must have an explicit NUL (CHR$0) termination

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:

        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.

This website uses cookies for visitor traffic analysis. By using the website, you agree with storing the cookies on your computer.More information
calling_20dll_20functions_20that_20return_20strings.txt · Last modified: 2018/04/14 17:08 by richardrussell