段错误 - c_void_p 到 c_byte 数组

segfault - c_void_p to c_byte array

我有一个简单的 c 函数,returns 一个字节数组和数组长度:

// base58.h
/* Return type for Decode */
struct Decode_return {
    void* r0;
    int r1;
};

// Decode decodes a modified base58 string to a byte slice, using BTCAlphabet
extern struct Decode_return Decode(char* p0);

我正在尝试从 python 中调用此 c 函数,如下所示:

// base58.py
from ctypes import *
base58 = CDLL('./base58.so')

class DecodeResponse(Structure):
    _fields_ = [
        ("r0", c_void_p),
        ("r1", c_int),
    ]

base58.Decode.restype = DecodeResponse

expect = bytes.fromhex("61")
print(expect.decode("utf-8"))

res = base58.Decode(c_char_p("2g".encode('utf-8')))

length = c_int(res.r1).value
print(length)

ArrayType = c_byte*(length)
pa = cast(c_void_p(res.r1), POINTER(ArrayType))

print(pa.contents[:])

不过,当我 运行 这样做时,我遇到了段错误。为什么 pa.contents 不可寻址?

$ python3 base58.py
a
1
[1]    21864 segmentation fault (core dumped)  python3 base58.py

如果我理解正确,这会将一个 int 转换为一个指针。

pa = cast(c_void_p(res.r1), POINTER(ArrayType))

我猜你想用 r0 替换 r1。我建议使用更好的命名方案。