How do you convert multistring to/from C# string collection?

前端 未结 3 1326
隐瞒了意图╮
隐瞒了意图╮ 2021-01-13 06:23

Multistrings (double null-terminated string of null-separated strings) are common in the Windows API. What\'s a good method for converting a multistring returned from an API

3条回答
  •  被撕碎了的回忆
    2021-01-13 06:45

    I've tested the StringArrayToMultiString method, using the ChangeServiceConfig() function to change the dependencies of a Windows service, and it works nicely for zero, one and many strings.

    In the meantime, I've worked out a solution for decoding a multistring received from an API call. For example, the SCardListReaders() function returns a multistring of PC/SC reader names. I declared this as:

    [DllImport("winscard.dll", CharSet = CharSet.Auto)]
    static extern int SCardListReaders(
        IntPtr context,
        string groups,
        char[] readers,
        ref uint readersLen
        );
    

    Note that the readers parameter, which returns the multistring, is declared as char[]. The return value is easily parsed and converted into a collection of strings:

    static string[] MultiStringToArray(
        char[] multistring
        )
    {
        List stringList = new List();
        int i = 0;
        while (i < multistring.Length)
        {
            int j = i;
            if (multistring[j++] == '\0') break;
            while (j < multistring.Length)
            {
                if (multistring[j++] == '\0')
                {
                    stringList.Add(new string(multistring, i, j - i - 1));
                    i = j;
                    break;
                }
            }
        }
    
        return stringList.ToArray();
    }
    

提交回复
热议问题