in python with ctypes change value of parameter in an object adress

33 Views Asked by At

I'm trying to program a linked list for a school activity, but for the library ctypes if I want to change the parameter of a object that stores an address only having the address of the object in question how do I do it.

For example, if I want to add a node at the end and I have the address of the last node(which is an object) I need to change the value from None to the address of the new node created, how can I do this?

also it's my first time asking a question sorry if I'm not giving enough detail, if there is any more information important to answer tell me

This is what I tried but obviously didn't work because I'm just making this_Node equal to the object and then changing this_Node itself and not the actual value in the address but I don't really know how to do it

    this_Node = ctypes.cast(this_pointer, ctypes.py_object).value
    this_Node.next = new_node_adress

the whole code

import ctypes 

class Node:
    def __init__(self,data,next):
        self.data = data
        self.next = next 
#initialise linked list
LinkedList = []
for i in range(0,10):
    LinkedList.append(Node(i,None))
for i in range(0,9):
    LinkedList[i].next = id(LinkedList[i+1])
root_pointer= id(LinkedList[0])
#print(ctypes.cast(root_pointer, ctypes.py_object).value.data)

#search in linked list 
def search_value(root_pointer,f):
    found = False
    this_address = root_pointer
    this_Node = ctypes.cast(root_pointer, ctypes.py_object).value
    this_pointer = this_Node.next
    while this_Node.next != None and found == False:
        #print(this_Node.data)
        if f == this_Node.data:
            found = True
            print(f,"was found in address",this_address)
        else:
            this_address = this_Node.next
            this_Node = ctypes.cast(this_pointer, ctypes.py_object).value
            this_pointer = this_Node.next
    if found ==False:
        print(f,"was not in the list")
    return found, this_address,this_Node,this_pointer

def end_add(root_pointer,new_node_adress):
    this_address = root_pointer
    this_Node = ctypes.cast(root_pointer, ctypes.py_object).value
    this_pointer = this_Node.next
    while this_Node.next != None:
        this_address = this_Node.next
        this_Node = ctypes.cast(this_pointer, ctypes.py_object).value
        this_pointer = this_Node.next
    this_Node.next = new_node_adress
    

f = 34
a = Node(34,None)
end_add(root_pointer,id(a))
#print(ctypes.cast(root_pointer, ctypes.py_object).value.data)
found,this_address,this_Node,this_pointer=search_value(root_pointer,f)

also sorry if its not very well structured but Im newish with python

0

There are 0 best solutions below