Home > Back-end >  circular struct in ctypes, python
circular struct in ctypes, python

Time:03-26

How to represent circular struct in python using ctypes?

A linked list can be represented in the following way in c

typedef struct LinkedList LinkedList;
typedef struct Node Node;

struct Node
{
    int value;
    Node* next;
};


struct LinkedList
{
    Node* start;
    int length;
};

How to represent the same struct in python using ctypes. I tried the following

from ctypes import *


class Node(Structure):
    _fields_ = [
        ("value", c_int),
        ("next", pointer(Node))
    ]

But the above gives the following error

NameError: name 'Node' is not defined

CodePudding user response:

You should read the documentation of ctypes, there you will find this:

>>> from ctypes import *
>>> class cell(Structure):
...     pass
...
>>> cell._fields_ = [("name", c_char_p),
...                  ("next", POINTER(cell))]
>>>

Something more


To reference a class inside a method you can do this:

# Don't do:
class Node:
    Node
# But:
class Node:
    def __init__(self):
        type(self)

When you want to use type hints for a class from inside itself, you have to do this:

from __future__ import annotations
  • Related