【问题标题】:Python ctypes: Object has no attribute ErrorPython ctypes:对象没有属性错误
【发布时间】:2021-06-04 18:45:29
【问题描述】:

这是c程序:

fqlib.h

typedef struct queue {
    int *que;       /* the actual array of queue elements */
    int head;       /* head index in que of the queue */
    int count;      /* number of elements in queue */
    int size;       /* max number of elements in queue */
} QUEUE;

/*
 * the library functions
 */
void qmanage(QUEUE **, int, int);   /* create or delete a queue */
void put_on_queue(QUEUE *, int);    /* add to queue */
void take_off_queue(QUEUE *, int *);    /* pull off queue */

fqlib.c

#include <stdio.h>
#include <stdlib.h>
#include "fqlib.h"

/*
 * create or delete a queue
 *
 * PARAMETERS:  QUEUE **qptr    space for, or pointer to, queue
 *      int flag    1 for create, 0 for delete
 *      int size    max elements in queue
 */
void qmanage(QUEUE **qptr, int flag, int size)
{
    if (flag){
        /* allocate a new queue */
        *qptr = malloc(sizeof(QUEUE));
        (*qptr)->head = (*qptr)->count = 0;
        (*qptr)->que = malloc(size * sizeof(int));
        (*qptr)->size = size;
    }
    else{
        /* delete the current queue */
        (void) free((*qptr)->que);
        (void) free(*qptr);
    }
}
// ...

我正在尝试从 QUEUE 的指针中获取头部。但它说

AttributeError:“QUEUE”对象没有属性“head”

from ctypes import *
so_file = "./fqlib.so"
myq = CDLL(so_file)

class QUEUE(Structure):
    pass

QUEUE.__fields__ = [
    ('que', POINTER(QUEUE)),
    ('head', c_int),
    ('count', c_int),
    ('size', c_int),
]

qmanage = myq.qmanage
qmanage.argtypes = [POINTER(POINTER(QUEUE)), c_int, c_int]
qmanage.restype = c_void_p

q = POINTER(QUEUE)()
qmanage(byref(q), c_int(1), c_int(10))
print(q.contents.head)

我是否以错误的方式从指针中获取数据?

【问题讨论】:

    标签: python c python-3.x ctypes


    【解决方案1】:

    更正:

    from ctypes import *
    
    so_file = "./fqlib.so"
    myq = CDLL(so_file)
    
    class QUEUE(Structure): # no need for forward declare with pass.  POINTER(QUEUE) was wrong
        # single underscores on each side of _fields_ (caused error seen)
        _fields_ = [('que', POINTER(c_int)),  # not POINTER(QUEUE)
                    ('head', c_int),
                    ('count', c_int),
                    ('size', c_int)]
    
    qmanage = myq.qmanage
    qmanage.argtypes = [POINTER(POINTER(QUEUE)), c_int, c_int]
    qmanage.restype = None # Use None for void.  c_void_p is void*
    
    q = POINTER(QUEUE)()
    qmanage(byref(q), 1, 10) # no need for c_int(1), c_int(10).  .argtypes knows.
    print(q.contents.head)
    

    【讨论】:

    • 谢谢。实际上是错字:)
    猜你喜欢
    • 2014-05-14
    • 1970-01-01
    • 2014-07-08
    • 2016-04-17
    • 2014-03-30
    • 2023-03-22
    • 2020-05-25
    • 2018-05-02
    相关资源
    最近更新 更多