Is there anyway to support structures in python and does it not support the normal keyword struct?
for eg:
struct node
{
unsigned dist[20];
unsigned from[20];
}rt[10];
How can i covert this into a python struct?
I think the Python's equivalent to C-structs is classes:
class Node:
def __init__(self):
self.dist_ = []
self.from_ = []
rt = []
from is a keyword in Python; that'll give a SyntaxError.Since the ordering of attributes (unless an OrderedDict or something is used to __prepare__ or otherwise build the class) is not necessarily in order of definition, if you wanted to be compatible with an actual C struct or rely on data being in some order, then the following is a base you should be able to use (using ctypes).
from ctypes import Structure, c_uint
class MyStruct(Structure):
_fields_ = [
('dist', c_uint * 20),
('from', c_uint * 20)
]
Even an empty class would do:
In [1]: class Node: pass
In [2]: n = Node()
In [3]: n.foo = [1,2,4]
In [4]: n.bar = "go"
In [8]: print n.__dict__
{'foo': [1, 2, 4], 'bar': 'go'}
In [9]: print n.bar
go
SimpleNamespace.@Abhishek-Herle
If I would have been in your situation, I might rely on Struct module in python.
Like, in your case C structure is:
struct node
{
unsigned dist[20];
unsigned from[20];
}rt[10];
So here basic idea is to convert C-Structure to python and vice a versa. I can roughly define above c-structure in below python code.
s = struct.Sturct('I:20 I:20')
Now, if I want to pack any values to this structure I can do, some thing like below.
dist = [1, 2, 3....20]
from = [1, 2, 3....20]
s.pack(*dist, *from)
print s #this would be binary representation of your C structure
Obviously, you can unpack back it using s.unpack method.
structkeyword "normal" indicates to me that you are thinking strictly in terms of a line-by-line translation of C into Python. I suggest at the very least you start by reading a tutorial on Python programming.structpackage.