Python ctypes:对象没有属性错误

2024-06-02 08:20:43 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是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);
    }
}
// ...

我正试图从队列指针上取头。但是它说

AttributeError: "QUEUE" object has no attribute "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)

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


Tags: oftheinsizequeueelementsdeletehead
1条回答
网友
1楼 · 发布于 2024-06-02 08:20:43

更正:

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)

相关问题 更多 >