python - 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
解决方案
如果我理解正确,这会将 int 转换为指针。
pa = cast(c_void_p(res.r1), POINTER(ArrayType))
我猜你想替换r1
为r0
. 我建议使用更好的命名方案。
推荐阅读
- assembly - 我无法在链接描述文件中指定 Rust 程序的起始偏移量是否有原因?
- sql-server - 在 WITH SCHEMABINDING 视图中使用别名会导致错误
- c# - Razor 页面路由到默认页面的问题
- testrail - 如何将日期字段从 csv 上传到 TestRail
- java - 我怎样才能要求 intellj 重新索引
- angular - 将 mat-datepicker 转换为字符串
- python - ImportError: dlopen(...), Symbol not found: _GEOSArea, Referenced From ..., 预期在:flat namespace
- formatting - Liquid:将逗号分隔的货币转换为点分隔
- javascript - 从网页向 Chrome 扩展程序发送数据
- linux - 如何检测或监听连接到 docker 容器的 ssh 活动?