User Tools

Site Tools


calling_20dll_20functions_20that_20return_20strings

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:

        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.

This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
calling_20dll_20functions_20that_20return_20strings.txt · Last modified: 2024/01/05 00:22 by 127.0.0.1