简体   繁体   中英

How to use C++ struct in struct in Python

I have to transfer the C++ code into Micro Python to Wipy platform. Currently, I've some problems with it, especially with accesing the variables from other structures

C++ code:

typedef struct {
    char id[100];
    int rssi;
} tag_info;

typedef struct {
    tag_info tag[20];
} tag_list;

typedef struct {
    int timestamp;
    tag_list tags;
    int heading;
    int airt;
} data_packet;

data_packet packet;

for (i = 0; i < total_amount_of_tags - 1; i++) {
            print_function("id", packet.tags.tag[i].id, destination); 
            print_function("rssi", packet.tags.tag[i].rssi, destination);
        }

My MicroPython code:

class tag_info:
    def __init__(self):
        self.id = ""
        self.rssi = 0

class tag_list:
    def __init__(self):
        self.tag = tag_info

class data_packet():
    def __init__(self):
        self.timestamp=0
        self.tags = tag_list
        self.heading=0
        self.airt=0

packet=data_packet()

for i in range(0, total_amount_of_tags -1)
    print_function('id',packet.tags.tag[i].id,destination)
    print_function("rssi", packet.tags.tag[i].rssi, destination); 

The problem in my code that I cant access tag[i] and further variables. Should I use inheritance or namedTuple in this case. If i try to use namedTuple from collections import namedTuple the following error message occurs: no module called collections , so I would prefer to avoid that library if possible

In the following:

self.tag = tag_info
You are assigning a class to a variable. I assume you meant to do:
 self.tag = tag_info() 
but if I understand correctly this is supposed to be a list of tag_info, so you actually need is:
 self.tag = [tag_info() for i in range(20)] 

same goes for:

 self.tags = tag_list() 

This is a bit confusing as to what the expected behavior is supposed to be. But it looks like you need to create 20 instances of tag_info . Also you need to instantiate your instances using () .

class tag_info:
    def __init__(self):
        self.id = ""
        self.rssi = 0

class tag_list:
    def __init__(self):
        self.tag = [tag_info() for _ in range(20)]

class data_packet():
    def __init__(self):
        self.timestamp=0
        self.tags = tag_list()
        self.heading=0
        self.airt=0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM