Re: why sturct size different between C and Python ctypes?
niki <[email protected]> Mon, 22 Feb 2016 10:51:01 +0200
| Newsgroups | gmane.comp.python.ctypes |
|---|---|
| Message-ID | <[email protected]> |
On 22.02.2016 09:52, Yang Liu wrote:
> Hi,all
>
> I am using ctypes today and a sturct size is differet in C and Python
> ctypes code
> here is my code
>
> C:
> #include<linux/netlink.h>
> #include<linux/inet_diag.h>
>
> int main(int argc, char *argv[])
> {
> struct {
> struct nlmsghdr nlh;
> struct inet_diag_req req;
> } nlreq;
> printf("nlreq: %d\n", sizeof(nlreq));
> return 0;
> }
>
> out:
> nlreq: 76
>
>
> Python:
> class nlmsghdr(ctypes.Structure):
> _fields_ = [
> ("len", ctypes.c_uint32),
> ("type", ctypes.c_uint16),
> ("flags", ctypes.c_uint16),
> ("seq", ctypes.c_uint32),
> ("pid", ctypes.c_uint32)]
>
> class Inet_diag_sockid(ctypes.Structure):
> _fields_ = [
> ("idiag_sport", ctypes.c_uint16.__ctype_be__),
> ("idiag_dport", ctypes.c_uint16.__ctype_be__),
> ("idiag_src", ctypes.c_uint32.__ctype_be__ * 4),
> ("idiag_dst", ctypes.c_uint32.__ctype_be__ * 4),
> ("idiag_if", ctypes.c_uint32),
> ("idiag_cookie", ctypes.c_uint32 * 2),
> ]
>
> class inet_diag_req(ctypes.Structure):
> _fields_ = [
> ("idiag_family", ctypes.c_uint8),
> ("idiag_src_len", ctypes.c_uint8),
> ("idiag_dst_len", ctypes.c_uint8),
> ("idiag_ext", ctypes.c_uint8),
> ("id", ctypes.POINTER(Inet_diag_sockid)),
> ("idiag_states", ctypes.c_uint32),
> ("idiag_dbs", ctypes.c_uint32)
> ]
>
> class nlmsg(ctypes.Structure):
> _fields_ = [
> ("nlh", nlmsghdr),
> ("req", Inet_diag_req)
> ]
>
> print ctypes.sizeof(nlmsg)
>
> out:
> 24
>
>
> why the same struct size is 76 inC and 24 in ctypes ?
Usually this is due to structure packing. Try with _pack_ values in struct.
HTH
Niki
------------------------------------------------------------------------------
Site24x7 APM Insight: Get Deep Visibility into Application Performance
APM + Mobile APM + RUM: Monitor 3 App instances at just $35/Month
Monitor end-to-end web transactions and take corrective actions now
Troubleshoot faster and improve end-user experience. Signup Now!
http://pubads.g.doubleclick.net/gampad/clk?id=272487151&iu=/4140