473,782 Members | 2,437 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 11666
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
2589
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
2506
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
5552
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
10129
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
2695
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
1131
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
12932
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
8510
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
9479
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
10146
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
10080
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9942
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8967
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5509
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4043
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
3639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2874
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.