Question on a C struct / Pointers and modules #13767
Replies: 2 comments 4 replies
-
@XT107234 Sorry I don't really see how the first C example maps to the structure you're defining with Here is how to populate that C structure from Python: >>> # Define string values
>>> apn = b"googleiot.com"
>>> network_name = b"hello world"
>>>
>>> # Define structure
>>> import uctypes
>>> c_cellular_t = { "MyNetworkName": 0 | uctypes.PTR, "myApn": 4 | uctypes.PTR, "rssiLevel": 8 | uctypes.UINT16 }
>>>
>>> # Create buffer and structure
>>> dbytes = bytearray(uctypes.sizeof(c_cellular_t, uctypes.LITTLE_ENDIAN))
>>> bmem = uctypes.struct(uctypes.addressof(dbytes), c_cellular_t, uctypes.LITTLE_ENDIAN)
>>>
>>> # Set fields in structure
>>> bmem.MyNetworkName = uctypes.addressof(network_name)
>>> bmem.myApn = uctypes.addressof(apn)
>>> bmem.rssiLevel = 72
>>>
>>> # Check resulting structure layout
>>> dbytes
bytearray(b'`\xd4\x01 \xe0\xce\x01 H\x00')
>>>
>>> # Verify struct is correct
>>> import struct
>>> apn_ptr, net_ptr, rssi = struct.unpack('<IIH', dbytes)
>>> uctypes.bytearray_at(apn_ptr, 10)
bytearray(b'hello worl')
>>> uctypes.bytearray_at(net_ptr, 10)
bytearray(b'googleiot.')
>>> rssi
72 |
Beta Was this translation helpful? Give feedback.
-
Thanks a lot @jimmo for the code, you can ignore netFlags (a "copy/paste" mistake). As far I can see, my problem came from the struct definition: MyNetworkName": ( 0 | uctypes.PTR, , uctypes.UINT8) where _ uctypes.UINT8)_ was leading to the issue. Btw, I don't understand something in your snippet:
Why '<IIH' ...shouldn't it be something like '<PPH' ? |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi all,
I m porting some existing C code to Micropython (and im not very familiar with it). Im currently trying to find a way to exchange a data buffer between the 2 worlds (Mpy and C mod), but i have 1 big problem (or question :) )...
From the Mpy side, i would like to fill a struct like below and send it to the C module:
I wrote the following Mpy code:
...and i can't assign the pointer, it fails :(
Any help will be welcome !!!
Beta Was this translation helpful? Give feedback.
All reactions