[issue5119] wide character parameter handling in ctypes

Amaury Forgeot d'Arc report at bugs.python.org
Tue Feb 3 02:39:25 CET 2009


Amaury Forgeot d'Arc <amauryfa at gmail.com> added the comment:

ctypes cannot guess the function signature, and does not know if the function 
expects strings or unicodes.

In your examples,
     ctypes.windll.user32.MessageBoxW(handle, text, caption, type)
will accept everything you pass, and create C values depending on the types of the 
actual values of the parameters: when you pass a unicode, ctypes uses a wchar_t* 
buffer; when you pass a narrow string, ctypes uses a char* buffer (and is wrong in 
this case).

In your Structure example, you do declare a kind of signature for the Structure.
ctypes is now able to convert the value you give into the declared type.

You can do the same thing with functions, if you provide the signature:

    MessageBox = ctypes.windll.user32.MessageBoxW
    MessageBox.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p,
                           ctypes.c_wchar_p, ctypes.c_int]
(or better, since this matches the documentation on msdn:)
    from ctypes.wintypes import *
    MessageBox.argtypes = [HWND, LPCWSTR, LPCWSTR, UINT]

And then you may indifferently pass strings or unicodes:
    MessageBox(None, u"café", "drink", 0)

----------
nosy: +amaury.forgeotdarc
resolution:  -> works for me
status: open -> pending

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue5119>
_______________________________________


More information about the Python-bugs-list mailing list