I've been trying to port this code to python, but there is something I do not quite understand in C++ (I do know a bit of C++ but this is beyond me):
typedef struct huffnode_s
{
struct huffnode_s *zero;
struct huffnode_s *one;
unsigned char val;
float freq;
} huffnode_t;
What I don't get is how huffnode_s can be within itself, I've never seen this before and don't quite understand it. What does this mean, and if someone can, what would be the python equivalent?
A structure can not refer itself directly. union VAL v; struct list * next; }; typedef struct list List; Creating lists...
Pointers to structures Although a structure cannot contain an instance of its own type, it can can contain a pointer to another structure of its own type, or even to itself.
Self Referential structures are those structures that have one or more pointers which point to the same type of structure, as their member.
The self-referential structure is a structure that points to the same type of structure. It contains one or more pointers that ultimately point to the same structure. Structures are a user-defined data structure type in C and C++.
huffnode_s
isn't within itself, only pointers to huffnode_s
are in there. Since a pointer is of known size, it's no problem.
This.
class Huffnode(object):
def __init__(self, zero, one, val, freq):
"""zero and one are Huffnode's, val is a 'char' and freq is a float."""
self.zero = zero
self.one = one
self.val = val
self.freq = freq
You can then refactor your various C functions to be methods of this class.
Or maybe this.
from collections import namedtuple
Huffnode = namedtuple( 'Huffnode', [ 'zero', 'one', 'val', 'freq' ] )
If you want your C functions to remain functions.
That's it.
h0 = Huffnode(None, None, 'x', 0.0)
h1 = Huffnode(None, None, 'y', 1.0)
h2 = Huffnode(h0, h1, 'z', 2.0)
That's all that's required.
it does not have a structure in itself. it has a pointer to that structure.
in memory struct huffnode_s would look like (32 bit machine):
|------------------ huffnode_s* zero - 4 bytes --------------|
|------------------ huffnode_s* one - 4 bytes----------------|
|unsigned char val - 1 byte + 3 bytes padding=======|
|------------------- float freq - 4 bytes -------------------------|
these sizes would vary machine to machine, and how it looks in memory is decided by compiler .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With