无法访问 const char 数组的值

Unable to access value of const char array

假设我在名为 libmylib.so 的 C 库中有以下代码:

static char mystr[9];

/* somewhere else this array is populated with a value 8 bytes or less */

const char *
get_mystr (void)
{
  return mystr;
}

从 Python 解释器,我调用以下内容

from ctypes import *
mylib = CDLL('libmylib.so')

加载库。现在,我将变量设置为 mystr

x = mylib.get_mystr()

如果我尝试检查 x 的值或它的任何属性,我会遇到分段错误。即使在提示符下键入 x. 后使用 TAB 查看可用的 fields/functions 也会导致段错误。

怎么回事?

编辑:如果我检查 x 本身,我会得到一个内存地址,正如预期的那样。如果我尝试检查 x.value 或查看可用字段,它会崩溃。

编辑 2:我尝试检查 static 声明是否是我的问题的根源,但没有它似乎表现相同。

@eryksun 指出 C 函数的 restype 默认为 int 并被解析为 Python 整数。

通过调用 mylib.get_mystr.restype = c_char_p,它现在可以正确解析为可以正确解码的 bytes 对象。