首页 > 解决方案 > segfault - c_void_p 到 c_byte 数组

问题描述

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

// 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

标签: pythonpython-3.xctypes

解决方案


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

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

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


推荐阅读