Norton Penguinion
Norton Penguinion

Reputation: 161

How do I convert c types to python integers without having it declared? - Python

Ugh, another programming question guys, haha.

So anyways, I became pretty interested in ctypes with python. ctypes basically allows you to call c variables within python (Awesome, I know) so here is how you declare variables with ctypes now:

import ctypes as c
class test(c.Structure):
   _fields_ = [
               ("example" , c.c_long),
               ...
              ]

Here's the thing though, whenever I use string formatting:

    print("test: %d" % (test.example)

it tells me that I needs it to be a Python Integer, not a C long.

Here's where it becomes complicated, because example isn't really declared, I can't do a .value method. It will return a syntax error. I can't declare example as a python integer because there is no way to do that. (at least, as far as I know)

Any help will be appreciated!

Upvotes: 0

Views: 190

Answers (1)

jfs
jfs

Reputation: 414089

test is a class; create an instance of test instead:

import ctypes as c

class test(c.Structure):
   _fields_ = [("example" , c.c_long)]

t = test(5)
print(t.example) # -> 5
print("%d" % t.example) # -> 5

Upvotes: 4

Related Questions