473,791 Members | 3,216 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Interconvert a ctypes.Structur e to/from a binary string?

Basically, I'd like to use the ctypes module as a much more descriptive
"struct" module.

Is there a way to take a ctypes.Structur e-based class and convert it
to/from a binary string?

Thanks,
-a
Aug 2 '08 #1
3 11667
On 2 Aug., 08:35, Andrew Lentvorski <bs...@allcaps. orgwrote:
Basically, I'd like to use the ctypes module as a much more descriptive
"struct" module.

Is there a way to take a ctypes.Structur e-based class and convert it
to/from a binary string?

Thanks,
-a
My first idea was :

from ctypes import *
from pickle import *

class T(Structure): pass

print dumps(T())

which raises an TypeError, "abstract class".

And then I found

http://osdir.com/ml/python.ctypes/2006-03/msg00009.html

Greetings, Uwe

Aug 2 '08 #2
On Aug 1, 11:35 pm, Andrew Lentvorski <bs...@allcaps. orgwrote:
Basically, I'd like to use the ctypes module as a much more descriptive
"struct" module.

Is there a way to take a ctypes.Structur e-based class and convert it
to/from a binary string?

Thanks,
-a
After chugging through the ctypes source code, I found that I can
abuse ctypes into doing what I want.

Here is how I did it. I can abuse
string_at(addre ssof(SomeCtypes Class), length) to get a binary string
out of ctypes while I use:

def analyze_elf_hea der(binaryData) :
headerSize = ctypes.sizeof(E lf32_Ehdr)
header = Elf32_Ehdr()

# Abuse ctypes to initialize from a string
bb = ctypes.create_s tring_buffer(bi naryData[0:headerSize])
ctypes.memmove( ctypes.addresso f(header), ctypes.addresso f(bb),
headerSize)

To jam stuff into a ctypes class. This seems like an oversight in the
module though. It would really be better if the class itself had
methods to init from/produce to a binary string.

However, I would prefer that somebody who actually knows ctypes to
weigh in here with comments about what I did.

Thanks,
-a
Aug 2 '08 #3
Andrew P. Lentvorski, Jr. <bs****@gmail.c omwrote:
On Aug 1, 11:35 pm, Andrew Lentvorski <bs...@allcaps. orgwrote:
Basically, I'd like to use the ctypes module as a much more descriptive
"struct" module.

Is there a way to take a ctypes.Structur e-based class and convert it
to/from a binary string?

Thanks,
-a

After chugging through the ctypes source code, I found that I can
abuse ctypes into doing what I want.

Here is how I did it. I can abuse
string_at(addre ssof(SomeCtypes Class), length) to get a binary string
out of ctypes while I use:

def analyze_elf_hea der(binaryData) :
headerSize = ctypes.sizeof(E lf32_Ehdr)
header = Elf32_Ehdr()

# Abuse ctypes to initialize from a string
bb = ctypes.create_s tring_buffer(bi naryData[0:headerSize])
ctypes.memmove( ctypes.addresso f(header), ctypes.addresso f(bb),
headerSize)

To jam stuff into a ctypes class. This seems like an oversight in the
module though. It would really be better if the class itself had
methods to init from/produce to a binary string.

However, I would prefer that somebody who actually knows ctypes to
weigh in here with comments about what I did.
I have found myself doing this quite a bit with ctypes. It is common
to get a block of data in which represents a stream of structures
which have to be unpicked and made into ctypes structs before use.
Making that stream is an equal challenge.

I've found a couple of ways of doing it.

Setup
>>from ctypes import *
class A(Structure):
... _fields_ = [("x", c_int)]
...
>>packet="\x02\ x01\x00\x00"
Eg to make a struct from a string
>>a = cast(packet, POINTER(A)).con tents
a.x
258
>>>
Or (this is identical to your method)
>>a = A()
a.x
0
>>memmove(addre ssof(a), packet, sizeof(a))
3083811008L
>>a.x
258

I think the second of those methods is promoted by the ctypes
documentation. I'm not sure about the lifetimes of the .contents in
the first method!

And the reverse
>>string_at(add ressof(a), sizeof(a))
'\x02\x01\x00\x 00'
>>>
Which I think is probably acceptable...

Some to/from binary methods would be nice, or failing that an explicit
section in the docs!

--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Aug 4 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2591
by: Thomas Heller | last post by:
ctypes 0.9.1 released - Sept 14, 2004 ===================================== Overview ctypes is a ffi (Foreign Function Interface) package for Python 2.3 and higher. ctypes allows to call functions exposed from dlls/shared libraries and has extensive facilities to create, access and manipulate
19
2507
by: Thomas Heller | last post by:
ctypes 0.9.2 released - Oct 28, 2004 ==================================== Overview ctypes is a ffi (Foreign Function Interface) package for Python 2.3 and higher. ctypes allows to call functions exposed from dlls/shared libraries and has extensive facilities to create, access and manipulate
3
5559
by: Lenard Lindstrom | last post by:
Posted in a previous thread was some Python code for accessing Window's Simple MAPI api using the ctypes module. http://groups-beta.google.com/group/comp.lang.python/msg/56fa74cdba9b7be9 This Simple MAPI module was Ian's completed version of an example I had posted in an earlier message. In it I had to set some pointer fields in a C structure to NULL. I was not happy with the solution I used so I made an inquiry on the ctypes-users...
12
10132
by: p.lavarre | last post by:
Q: The C idea of (pv != NULL) is said most directly in Python ctypes how? A: We are of course supposed to write something like: def c_not_null(pv): return (ctypes.cast(pv, ctypes.c_void_p).value != None) Yes?
7
7048
by: p.lavarre | last post by:
How do I vary the byte offset of a field of a ctypes.Structure? How do I "use the dynamic nature of Python, and (re-)define the data type after the required size is already known, on a case by case basis"? \\\ For example, suppose sometimes I receive the value '\x03hi' + \x04bye' for the struct:
3
2697
by: Chris AtLee | last post by:
Sorry for the repeat post...I'm not sure if my first post (on May 30th) went through or not. I've been trying to write a PAM module using ctypes. In the conversation function (my_conv in the script below), you're passed in a pam_response** pointer. You're supposed to allocate an array of pam_response's and set
0
1133
by: p.lavarre | last post by:
http://wiki.python.org/moin/ctypes now tries to answer: '''FAQ: How do I copy bytes to Python from a ctypes.Structure?''' '''FAQ: How do I copy bytes to a ctypes.Structure from Python?''' '''FAQ: Why should I fear using ctypes.memmove?''' '''FAQ: How do I change the byte length of a ctypes.Structure?''' '''FAQ: How do I say memcpy?''' '''FAQ: How do I say offsetof?''' '''FAQ: How do I say uchar?''' '''FAQ: How do I say ((void *) -1)?'''
6
12951
by: Jack | last post by:
I'm not able to build IP2Location's Python interface so I'm trying to use ctypes to call its C interface. The functions return a pointer to the struct below. I haven't been able to figure out how I should declare the return type of the functions and read the fields. Any hint is appreciated. typedef struct { char *country_short; char *country_long;
4
8521
by: Neal Becker | last post by:
In an earlier post, I was interested in passing a pointer to a structure to fcntl.ioctl. This works: c = create_string_buffer (...) args = struct.pack("iP", len(c), cast (pointer (c), c_void_p).value) err = fcntl.ioctl(eos_fd, request, args) Now to do the same with ctypes, I have one problem.
0
9517
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10428
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10207
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7537
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5435
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5559
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4110
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3718
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2916
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.