0

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.

wanze
  • 43
  • 1
  • 10
  • You need to add a bit more information to your question. I think you mean to port the C# code to python. I also think you are importing code from a dll, but you didn't specify what dll that may be. You are also referencing `ZwCommDll` but it is not explained where this comes from. – Hintham Oct 29 '18 at 08:35
  • Possible duplicate of [ctypes - Beginner](https://stackoverflow.com/questions/5081875/ctypes-beginner) – Hintham Oct 29 '18 at 08:38
  • The Dll is from anthoer company, I can not tell more info about it. – wanze Oct 29 '18 at 08:39
  • The basic ctypes datatype how to pass it I already know it . My problem is focused on the StringBuilder Datatype. – wanze Oct 29 '18 at 08:42
  • @wanze Even if the DLL is from another company you should have a header file describing the parameter and return types. – Mark Tolonen Oct 29 '18 at 15:49

1 Answers1

1

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>'
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • Thanks that's should be the answer, if the dll function doesnot have some problem. but here I still got some error. Did you know what's the situation going on? Traceback (most recent call last): File "tests\test_dll2.py", line 21, in lib_tool.GetCPUMachineKey(buff,128) ValueError: Procedure probably called with not enough arguments (84 bytes missing) – wanze Oct 30 '18 at 01:27
  • @wanze Use WinDLL instead of CDLL. If you still have issues update your question with your Python code. You should do that anyway otherwise we’re just guessing. See the [mcve] guidelines. It would help to see the function prototype as well. – Mark Tolonen Oct 30 '18 at 12:54