1

I'm learning ctypes module in python. I have the following code:

code

import sys
print(sys.version)
import ctypes
libc = ctypes.CDLL("/lib/x86_64-linux-gnu/libc.so.6")
print(libc)
for x in "我学Python!":
    print("'%s'" % x, libc.iswalpha(
       ord(x)
    ))

libc.wctype.argtypes = [ctypes.c_char_p]
alpha_wctype = libc.wctype(b'print')
print(type(alpha_wctype))
libc.iswctype.restype = ctypes.c_int
print(libc.iswctype(ord("我"), alpha_wctype))

output

3.7.7 (default, May  7 2020, 21:25:33) 
[GCC 7.3.0]
<CDLL '/lib/x86_64-linux-gnu/libc.so.6', handle 7f1d5b9e24f0 at 0x7f1d5a498f10>
'我' 1
'学' 1
'P' 1024
'y' 1024
't' 1024
'h' 1024
'o' 1024
'n' 1024
'!' 0
<class 'int'>
Fatal Python error: Segmentation fault

Current thread 0x00007f1d5b9dd740 (most recent call first):
  File "test2.py", line 15 in <module>
[1]    12178 segmentation fault  python -X faulthandler test2.py

So why the last line produced a segmentation fault, how can I use iswctype correctly using ctypes?

1 Answer 1

1

wctype doesn't return an int but rather a wctype_t. Python doesn't have a portable ctypes type for this, but it's probably an unsigned long on your system, so do libc.wctype.restype = ctypes.c_ulong. Similarly, you need to specify the argument types for iswctype, like this: libc.iswctype.argtypes = [ctypes.c_uint, ctypes.c_ulong]. By not doing those things, you were truncating the alpha_wctype value, which was causing the segfault.

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

2 Comments

Yes, thanks a lot. I thought these types are c_ushort. But how can i makesure these types, without searching the libc code? Is there any pythonic way?
@MengZhao I don't think so. I looked through docs.python.org/3/library/ctypes.html but I don't see any better way to do it.

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.