473,325 Members | 2,805 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,325 software developers and data experts.

Interconvert a ctypes.Structure 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.Structure-based class and convert it
to/from a binary string?

Thanks,
-a
Aug 2 '08 #1
3 11589
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.Structure-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.Structure-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(addressof(SomeCtypesClass), length) to get a binary string
out of ctypes while I use:

def analyze_elf_header(binaryData):
headerSize = ctypes.sizeof(Elf32_Ehdr)
header = Elf32_Ehdr()

# Abuse ctypes to initialize from a string
bb = ctypes.create_string_buffer(binaryData[0:headerSize])
ctypes.memmove(ctypes.addressof(header), ctypes.addressof(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.comwrote:
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.Structure-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(addressof(SomeCtypesClass), length) to get a binary string
out of ctypes while I use:

def analyze_elf_header(binaryData):
headerSize = ctypes.sizeof(Elf32_Ehdr)
header = Elf32_Ehdr()

# Abuse ctypes to initialize from a string
bb = ctypes.create_string_buffer(binaryData[0:headerSize])
ctypes.memmove(ctypes.addressof(header), ctypes.addressof(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)).contents
a.x
258
>>>
Or (this is identical to your method)
>>a = A()
a.x
0
>>memmove(addressof(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(addressof(a), sizeof(a))
'\x02\x01\x00\x00'
>>>
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
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...
19
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...
3
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...
12
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,...
7
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...
3
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...
0
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?'''...
6
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...
4
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),...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.