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.

5
  • 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. Commented Oct 29, 2018 at 8:35
  • Possible duplicate of ctypes - Beginner Commented Oct 29, 2018 at 8:38
  • The Dll is from anthoer company, I can not tell more info about it. Commented Oct 29, 2018 at 8:39
  • The basic ctypes datatype how to pass it I already know it . My problem is focused on the StringBuilder Datatype. Commented Oct 29, 2018 at 8:42
  • @wanze Even if the DLL is from another company you should have a header file describing the parameter and return types. Commented Oct 29, 2018 at 15:49

1 Answer 1

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>'
Sign up to request clarification or add additional context in comments.

2 Comments

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 <module> lib_tool.GetCPUMachineKey(buff,128) ValueError: Procedure probably called with not enough arguments (84 bytes missing)
@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 minimal reproducible example guidelines. It would help to see the function prototype as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.