Search code examples
c#pythonctypesstringbuilder

How to pass the StringBuilder parameter in C# to ctypes in python, which is not the normal ctypes supported datatype


I am working on the project, which there is c# project use the dll like that:

    public string GetMachineKey()
    {
        StringBuilder buff = new StringBuilder();
        buff.Length = 128;
        ZwCommDll.GetCPUMachineKey(buff, 128);
        string mk = buff.ToString();
        return mk;
    }

and I want do it similily in python use the ctypes.

But i am so comfused by the StringBuilder DataType.

Thanks very much your help.


Solution

  • Use ctypes.create_unicode_buffer() to generate a writable text string buffer (wchar_t*) for an API. Use ctypes.create_string_buffer() for a writable byte string buffer (char*). Something like the following should work if the function takes a char*:

    >>> import ctypes
    >>> buff = ctypes.create_string_buffer(128)
    >>> ZwCommDll.GetCPUMachineKey(buff,128)
    >>> buff.value
    b'<returned string>'