【问题标题】:Passing a structure pointer to a function in ctypes将结构指针传递给 ctypes 中的函数
【发布时间】:2011-08-19 09:47:08
【问题描述】:

我正在尝试在 ctypes 中重做 Misaka 模块,但是当我尝试使用 bufputs 时出现错误(请参阅第二个代码示例的结尾)。当我将指针传递给我使用pointer(b) 的函数时。这不起作用,byref(b) 也不起作用。

这是函数签名:

/* bufputs • appends a NUL-terminated string to a buffer */
void
bufputs(struct buf *, const char*);

这是我的代码:

>>> from ctypes import *
>>> sundown = cdll.LoadLibrary('./libsundown.so.1')
>>> sundown
<CDLL './libsundown.so.1', handle 1e2f190 at 1bea0d0>
>>> # OUT: <CDLL './libsundown.so.1', handle 2840d80 at 2797290>
>>> class buf(Structure):
...     _fields_ = [
...         ('data', c_char_p),
...         ('size', c_size_t),
...         ('asize', c_size_t),
...         ('unit', c_size_t),
...         ('ref', c_int)]
... 
>>> sundown.bufnew.argtypes = [c_size_t]
>>> sundown.bufnew.restype = buf
>>> b = sundown.bufnew(c_size_t(1024))
>>> sundown.bufputs.argtypes = [POINTER(buf), c_char_p]
>>> s = c_char_p('this is a test')
>>> sundown.bufputs(pointer(b), s)
python2: malloc.c:3574: mremap_chunk: Assertion `((size + offset) & (mp_.pagesize-1)) == 0' failed.
Aborted

我不知道我做错了什么。

【问题讨论】:

  • 我对您使用的库不熟悉,但是 POINTER 是否创建了 buf 类的实例(已解决的示例)?
  • 如果您找到答案,您应该回答并接受您自己的问题。 :)
  • 只需将解决方案作为答案发布并接受即可。不然我就偷了。容易代表。 :D

标签: python c ctypes


【解决方案1】:

OP的解决方案,最初发布在问题中

class buf(Structure):
    _fields_ = [
        ('data', c_char_p),
        ('size', c_size_t),
        ('asize', c_size_t),
        ('unit', c_size_t),
        ('ref', c_int)
    ]
buf_p = POINTER(buf)

sundown.bufnew.argtypes = [c_size_t]
sundown.bufnew.restype = buf_p
sundown.bufgrow.argtypes = [buf_p, c_size_t]
sundown.bufputs.argtypes = [buf_p, c_char_p]

ib = buf()

# ctypes does this internally:
# memset(byref(ib), 0x0, sizeof(buf))

text = 'this is some text'
ib.data = text
ib.size = len(text)

ob = sundown.bufnew(128)
sundown.bufgrow(ob, int(math.ceil(ib.size * 1.4)))

sundown.bufputs(ob, 'test')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 2015-09-09
    • 2020-05-15
    • 1970-01-01
    • 2011-05-20
    • 2021-07-17
    • 1970-01-01
    相关资源
    最近更新 更多