简体   繁体   中英

Segmentation Fault when call iswctype function in libc.so.6 using python ctypes

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM