如何在lldb中打印wchar_t字符串?

Dav*_*Lin 4 lldb

鉴于wchar_t* str;哪个指向以null结尾的utf32(或utf16)字符串,我应该使用什么命令在lldb中打印它?

Jas*_*nda 9

我假设您要将其打印为utf8.它有点涉及 - 你需要在python中为类型创建一个汇总提供程序,它返回一个utf8字符串进行打印.但这并不是特别复杂.创建一个类似于~/lldb/wcharsummary.py内容的小python文件

import lldb
def wchar_SummaryProvider(valobj, dict):
  e = lldb.SBError()
  s = u'"'
  if valobj.GetValue() != 0:
    i = 0
    newchar = -1
    while newchar != 0:
      # read next wchar character out of memory
      data_val = valobj.GetPointeeData(i, 1)
      size = data_val.GetByteSize()
      if size == 1:
        newchar = data_val.GetUnsignedInt8(e, 0)    # utf-8
      if size == 2:
        newchar = data_val.GetUnsignedInt16(e, 0)   # utf-16
      if size == 4:
        newchar = data_val.GetUnsignedInt32(e, 0)   # utf-32
      else:
        return '<error>'
      if e.fail:
        return '<error>'
      i = i + 1
      # add the character to our string 's'
      if newchar != 0:
        s = s + unichr(newchar)
  s = s + u'"'
  return s.encode('utf-8')
Run Code Online (Sandbox Code Playgroud)

将其加载到lldb并将此python函数设置为wchar_t*的摘要提供程序; 最容易将其放入您的~/.lldbinit文件中以便重复使用:

command script import ~/lldb/wcharsummary.py
type summary add -F wcharsummary.wchar_SummaryProvider "wchar_t *"
Run Code Online (Sandbox Code Playgroud)

然后给出一些在32位wchar_t中有一些utf32编码字符的源码,

NSString *str = @"?????";  // 5 characters long
wchar_t *str_utf32_wchar = (wchar_t*) [[str dataUsingEncoding:NSUTF32StringEncoding] bytes];
Run Code Online (Sandbox Code Playgroud)

lldb将为我们打印utf8:

Process 22278 stopped
* thread #1: tid = 0x1c03, 0x0000000100000e92 a.out`main + 146 at a.m:11, stop reason = step over
    #0: 0x0000000100000e92 a.out`main + 146 at a.m:11
   8    
   9        NSString *str = @"?????";  // 5 characters long
   10       wchar_t *str_utf32_wchar = (wchar_t*) [[str dataUsingEncoding:NSUTF32StringEncoding] bytes];
-> 11       printf ("0x%llx 0x%llx 0x%llx 0x%llx\n", (uint64_t) str_utf32_wchar[0], (uint64_t) str_utf32_wchar[1], 
   12                                                (uint64_t) str_utf32_wchar[2], (uint64_t) str_utf32_wchar[3]);
   13   
   14       [pool release];

(lldb) fr va
(NSAutoreleasePool *) pool = 0x0000000100108190
(NSString *) str = 0x0000000100001068 @"?????"
(wchar_t *) str_utf32_wchar = 0x0000000100107f80 "?????"

(lldb) p str_utf32_wchar
(wchar_t *) $0 = 0x0000000100107f80 "?????"

(lldb) x/16b `str_utf32_wchar`
0x100107f80: 0xff 0xfe 0x00 0x00 0x53 0x30 0x00 0x00
0x100107f88: 0x93 0x30 0x00 0x00 0x6b 0x30 0x00 0x00
(lldb) 
Run Code Online (Sandbox Code Playgroud)