wanze
wanze

Reputation: 51

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.

Upvotes: 0

Views: 394

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177971

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>'

Upvotes: 1

Related Questions