1

Which data type should be used in this stringUpcase function in my DLL file

void __cdecl stringUpcase(char IN_str[], char OUT_str[], int32_t len);

I am trying ctype.c_char_p in Python 3.6 and This function should return the uppercase string "HELO" in OUT_str variable.

dl = ctypes.cdll.LoadLibrary("path/of/dll/file.dll")

IN_str = 'helo'
OUT_str = ''
IN_len = len(IN_str)

dl.stringUpcase.restype = ctypes.c_void_p
dl.stringUpcase.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int32]

dl.stringUpcase(IN_str, OUT_str, IN_len);

Console error output is

 line 21, in <module>
    dl.stringUpcase(IN_str, OUT_str, IN_len);
ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type

Thank you for any help you can provide.

2
  • strCnt or stringUpcase? Commented Jul 4, 2017 at 13:45
  • sorry my mistake ... It is stringUpcase function Commented Jul 4, 2017 at 15:27

1 Answer 1

2

You are trying to pass python string as an argument of type c_char_p. Python3 unlike python2 is pretty strict about typing in ctypes.

The working sample would look like this.

import ctypes

ins = ctypes.c_char_p(b'helo') 
lens = len(ins.value)
outs = ctypes.create_string_buffer(lens+1)
lib = ctypes.cdll.LoadLibrary("./upper.so")

lib.stringUpcase.restype = None
lib.stringUpcase.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int32]

lib.stringUpcase(ins, outs, lens)

print(outs.value)

Pay attention to the fact that c_char_p points to a zero-terminated string, so len argument is redundant here. Moreover to construct c_char_p you need to pass bytes object or and integer address rather than just a string, to be able to use string as an argument you need to use c_wchar_p type and wchar_t* in your library respectively.

One more thing to pay attention to is the fact that your C function does not allocate memory so you need for outs to be large enough to contain the result.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you it works really good, but the output is b'HELO' and I would like to transform it back to "python" string. so the result will be only HELO How is it possible?
@MichalMarcin decode them in some encoding, like this print(outs.value.decode('ascii'))

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.