3

How can I use the ctypes "cast" function to cast one integer format to another, to obtain the same effect as in C:

int var1 = 1;
unsigned int var2 = (unsigned int)var1;

?

4 Answers 4

5
>>> cast((c_int*1)(1), POINTER(c_uint)).contents
c_uint(1L)
>>> cast((c_int*1)(-1), POINTER(c_uint)).contents
c_uint(4294967295L)
Sign up to request clarification or add additional context in comments.

Comments

3

Simpler than using cast() is using .value on the variable:

>>> from ctypes import *
>>> x=c_int(-1)
>>> y=c_uint(x.value)
>>> print x,y
c_long(-1) c_ulong(4294967295L)

Comments

2

Integer to Structure typecasting

from ctypes import *

class head(Structure):
    _fields_=[
              ('x',c_ubyte),
              ('y',c_ubyte)
             ]

x = c_uint(0x3234)
px= cast(pointer(x),POINTER(head))

print(px[0].x)
print(px[0].y)

Comments

1

You may want to have a look at http://docs.python.org/2/library/ctypes.html#type-conversions

An example is ctypes.cast((ctype.c_byte*4)(), ctypes.POINTER(ctypes.c_int))

1 Comment

Thanks for the reply. I have read the documentation, but I am still unclear as to how to perform the conversion mentioned in my post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.