473,769 Members | 1,618 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

FAQ: how to vary the byte offset of a field of a ctypes.Structur e

How do I vary the byte offset of a field of a ctypes.Structur e?

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:

class Struct34(ctypes .Structure):
_pack_ = 1
_fields_ = [('first', 3 * ctypes.c_ubyte) ,
('second', 4 * ctypes.c_ubyte)]

but then sometimes instead I receive the value '\x05left' + \x06right'
for the struct:

class Struct56(ctypes .Structure):
_pack_ = 1
_fields_ = [('first', 5 * ctypes.c_ubyte) ,
('second', 6 * ctypes.c_ubyte)]

Thus in general I receive (0xFF ** 2) possible combinations of field
lengths.

///

How do I declare all those hugely many simply regular combinations as
one CTypes.structur e?

I also need to do series of 3 or 4 or 5 strings, not just 2 strings.
But always the byte offsets of the subsequent fields vary when the
byte sizes of the preceding fields vary. The byte size of the
enclosing packed struct varies as the length of the packed bytes it
contains.

The errors I get as I try techniques that don't work include:

AttributeError: '_fields_' must be a sequence of pairs
AttributeError: _fields_ is final
ValueError: Memory cannot be resized because this object doesn't own
it
TypeError: incompatible types, c_ubyte_Array_2 instance instead of
c_ubyte_Array_1 instance

How do I change the offset of a field of a ctypes.Structur e?

Is the answer to contribute to the next version of CTypes? Or is this
feature already supported somehow?

Curiously yours, thank in advance,

http://www.google.com/search?q=ctypes+variable+size
http://www.google.com/search?q=ctypes+variable+length
http://www.google.com/search?q=ctypes+variable+offset
http://www.google.com/search?q=ctype...+of+strings%22
http://www.google.com/search?q=ctype...byte+offset%22
http://www.google.com/search?q=ctype...byte+offset%22

May 31 '07 #1
7 7038
p.*******@ieee. org wrote:
How do I vary the byte offset of a field of a ctypes.Structur e?

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:

class Struct34(ctypes .Structure):
_pack_ = 1
_fields_ = [('first', 3 * ctypes.c_ubyte) ,
('second', 4 * ctypes.c_ubyte)]

but then sometimes instead I receive the value '\x05left' + \x06right'
for the struct:

class Struct56(ctypes .Structure):
_pack_ = 1
_fields_ = [('first', 5 * ctypes.c_ubyte) ,
('second', 6 * ctypes.c_ubyte)]

Thus in general I receive (0xFF ** 2) possible combinations of field
lengths.

///

How do I declare all those hugely many simply regular combinations as
one CTypes.structur e?

I also need to do series of 3 or 4 or 5 strings, not just 2 strings.
But always the byte offsets of the subsequent fields vary when the
byte sizes of the preceding fields vary. The byte size of the
enclosing packed struct varies as the length of the packed bytes it
contains.

The errors I get as I try techniques that don't work include:

AttributeError: '_fields_' must be a sequence of pairs
AttributeError: _fields_ is final
ValueError: Memory cannot be resized because this object doesn't own
it
TypeError: incompatible types, c_ubyte_Array_2 instance instead of
c_ubyte_Array_1 instance

How do I change the offset of a field of a ctypes.Structur e?

Is the answer to contribute to the next version of CTypes? Or is this
feature already supported somehow?

Curiously yours, thank in advance,
How about something like:

class fooStruct(ctype s.Structure):
_pack_ = 1
_fields_=[]
def __init__(self, fields):
self._fields_=f ields
ctypes.Structur e.__init__(self )

a=fooStruct([('first', 3*ctypes.c_ubyt e),
('second', 4*ctypes.c_ubyt e)])

print a._fields_
-Larry
May 31 '07 #2
p.*******@ieee. org schrieb:
How do I vary the byte offset of a field of a ctypes.Structur e?

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:

class Struct34(ctypes .Structure):
_pack_ = 1
_fields_ = [('first', 3 * ctypes.c_ubyte) ,
('second', 4 * ctypes.c_ubyte)]

but then sometimes instead I receive the value '\x05left' + \x06right'
for the struct:

class Struct56(ctypes .Structure):
_pack_ = 1
_fields_ = [('first', 5 * ctypes.c_ubyte) ,
('second', 6 * ctypes.c_ubyte)]

Thus in general I receive (0xFF ** 2) possible combinations of field
lengths.

///

How do I declare all those hugely many simply regular combinations as
one CTypes.structur e?

I also need to do series of 3 or 4 or 5 strings, not just 2 strings.
But always the byte offsets of the subsequent fields vary when the
byte sizes of the preceding fields vary. The byte size of the
enclosing packed struct varies as the length of the packed bytes it
contains.
Often it helps to ask yourself the question: How would I do this in C?

IMO, the answer to this question, applied to your problem, would be:
*Not* by using a structure. A structure is fine if the definition is fixed,
or at most has *one* variable sized field at the very end. Nothing
is true for your problem.

Thomas

May 31 '07 #3
ctypes.sizeof(a ) is still zero, as if ctypes.Structur e.__init__
fetches a.__class__._fi elds_ rather than a._fields_

May 31 '07 #4
""" Thomas,

Ouch ouch I must have misunderstood what you meant by "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".

Do you have an example of what you meant? I searched but did not find.
Are those your words?

Yes, to declare strings of strings in Python would be to express a
familiar idea that I don't know how to say well in C.

These are standard structs that I exchange with third parties, e.g.,
me editing Class files read later by a Java interpreter, so I can't
avoid having to deal with this complexity designed into them. For
discussion I've simplified the problem: back in real life I have a few
dozen variations of structs like this to deal with.

The following Python mostly works, but only at the cost of rewriting
the small part of CTypes that I need for this app.
"""

import binascii
import struct

class Struct:

def __init__(self, declarations = []):

"""Add initial values to self and list the names declared."""

names = []
for (initial, name) in declarations:
names += [name]
python = ' '.join(['self.' + name, '=',
'initial'])
exec python
self._names_ = names

def _fields_(self):

"""List the fields."""

fields = []
for name in self._names_:
python = 'self.' + name
fields += [eval(python)]
return fields

def _pack_(self):

"""Pack a copy of the fields."""

packs = ''
for field in self._fields_() :
packs += field._pack_()
return packs

def _size_(self, bytes = None):

"""Count the bytes of the fields."""

return len(self._pack_ ())

def _unpack_(self, bytes):

"""Count the bytes of a copy of the fields."""

offset = 0
for field in self._fields_() :
size = field._size_(by tes[offset:])
field._unpack_( bytes[offset:][:size])
offset += size
if offset != len(bytes):
why = ('_unpack_ requires a string argument'
'of length %d' % offset)
raise struct.error(wh y)

class Field(Struct):

"""Contain one value."""

def __init__(self, value = 0):
self._value_ = value

def _pack_(self):
raise AttributeError( 'abstract')

def _unpack_(self, bytes):
raise AttributeError( 'abstract')

class Byte(Field):

"""Contain one byte."""

def _pack_(self):
return struct.pack('B' , self._value_)

def _unpack_(self, bytes):
self._value_ = struct.unpack(' B', bytes)[0]

class ByteArray(Field ):

"""Contain the same nonnegative number of bytes always."""

def _pack_(self):
return self._value_

def _unpack_(self, bytes):
if len(bytes) == len(self._value _):
self._value_ = bytes
else:

why = ('_unpack_ requires a string argument'
'of length %d' % len(self._value _))
raise struct.error(wh y)

class Symbol(Struct):

"""Contain a count of bytes."""

def __init__(self, value = ''):
Struct.__init__ (self, [
(Byte(), 'length'),
(ByteArray(valu e), 'bytes')])
self._pack_()
def _size_(self, bytes = None):
return ord(bytes[0])

def _pack_(self):
self.length = Byte(self.lengt h._size_() +
self.bytes._siz e_())
return Struct._pack_(s elf)

class TwoSymbols(Stru ct):

"""Contain two Symbols."""

def __init__(self, values = ['', '']):
Struct.__init__ (self, [
(Symbol(values[0]), 'first'),
(Symbol(values[1]), 'second')])

zz = Symbol()
print binascii.hexlif y(zz._pack_()). upper()
# 01

zz = Symbol()
zz.bytes = ByteArray('left ')
zz._unpack_(zz. _pack_()) ; print repr(zz._pack_( ))
# '\x05left'

zz = Symbol()
zz.bytes = ByteArray('righ t')
zz._unpack_(zz. _pack_()) ; print repr(zz._pack_( ))
# '\x06right'

zz = TwoSymbols()
zz.first.bytes = ByteArray('hi')
zz.second.bytes = ByteArray('bye' )
zz._unpack_(zz. _pack_()) ; print repr(zz._pack_( ))
# '\x03hi\x04bye'

print zz._size_()
# 7

yy = '''
def yyFunc(self):
return [self.length, self.bytes]
'''
exec yy
Symbol._fields_ = yyFunc
zz = TwoSymbols(['alef', 'bet'])
zz._unpack_(zz. _pack_()) ; print repr(zz._pack_( ))

May 31 '07 #5
I see that changing self._fields_ doesn't change ctypes.sizeof(s elf).

I guess ctypes.Structur e.__init__(self ) fetches
self.__class__. _fields_ not self._fields_.

Jun 1 '07 #6
Often it helps to ask yourself the question: How would I do this in C? ...
>
*Not* by using a structure. A structure is fine if the definition is fixed,
or at most has *one* variable sized field at the very end.
http://docs.python.org/lib/module-pickle.html
might be near where I'll find concise Python ways of pickling and
unpickling the (0xFF ** N) possible ways of packing N strings of byte
lengths of 0..xFE together ...

I notice by now I need what ctypes does well often enough that I have
to make my corrupt copy of a subset of ctypes coexist with ctypes per
se. So I have two different BYTE definitions. One is the
ctypes.c_ubyte. The other is my corrupt copy. And likewise for a big-
endian BIG_WORD and so on. So I end up naming the one BYTE and the
other BITE, the one BIG_WORD and the other BIG_WURD, yuck.

Jun 2 '07 #7
http://docs.python.org/lib/module-pickle.html
... concise Python ways of pickling and unpickling
the (0xFF ** N) possible ways of
packing N strings of byte lengths of 0..xFE together ...
Aye, looks like an exercise left open for the student to complete:
>>pickle.dumps( "")
"S''\np0\n. "
>>>
pickle.dumps( "abc")
"S'abc'\np0 \n."
>>>
pickle.loads( pickle.dumps("a bc"))
'abc'
>>>
pickle.dumps( ctypes.c_ubyte( 0))
....
TypeError: abstract class
>>>
Jun 4 '07 #8

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

Similar topics

7
2780
by: Vince | last post by:
Hi, I am starting to play with with C++ and I have some questions. I need to parse a XML file that describes a smart card file structure and to initialize my data structure. First I chose this structure : A CCardObject has files (index by SFID) and each file has records(indexed by RecNo) and each record can be splitted into data(index by string).
11
3476
by: Bradford Chamberlain | last post by:
I work a lot with multidimensional arrays of dynamic size in C, implementing them using a single-dimensional C array and the appropriate multipliers and offsets to index into it appropriately. I tend to iterate over subsets of these arrays by walking a pointer and an offset per dimension across their dimensions. I've found that this tends to result in more performance in a portable manner than doing explicit indexing calculations and...
7
6747
by: War Eagle | last post by:
I have two byte arrays and a char (the letter S) I was to concatenate to one byte array. Here is what code I have. I basically want to send this in a one buffer (byte array?) through a socket. SWXXXXXXXXXYYYYZZZZZZZZZZZZZZZZZZZZZ Where S is the command for SEND and should just be the character S. Where W is a byte representing how long the filename (testfile.txt) is. In this case 12. Where XXXXXXX is converted from a string that...
5
1604
by: Olaf Baeyens | last post by:
I have another problem, maybe it is simple to fix. I have this: byte Test=new byte; But I now want to have a second pointer Test2 to point to a location inside this Test. But with no copying. Something like this.
14
2519
by: Ronodev.Sen | last post by:
i have a C# program that is sending data in a byte array through a socket. the VC++ application server receives data in teh following format.... typedef struct advice { header sHdr; char Code; char pn;
5
3470
by: moni | last post by:
Hey, My buffer contains a short int, some char, and a structure in form of a byte array. Read the string as: TextBox4.Text = System.Text.Encoding.ASCII.GetString(buffer1, 0, 31); Read the int as:
6
12923
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;
3
11665
by: Andrew Lentvorski | last post by:
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
5
4217
by: castironpi | last post by:
Hi all, I have a mmap and a data structure in it. I know the structure's location in the mmap and what structure it is. It has a ctypes definition. I want to initialize a ctypes object to point to a part of the mmap. Here is my attempt:
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
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
10045
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...
0
8870
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...
1
7408
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
6673
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5298
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...
1
3958
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
3
2815
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.