如何在不声明C类型的情况下将其转换为python整数? -Python [英] How do I convert c types to python integers without having it declared? - Python
问题描述
呃,另一个编程问题的人,哈哈。
Ugh, another programming question guys, haha.
所以无论如何,我对使用python的ctype变得非常感兴趣。
ctypes基本上允许您在python中调用c变量(太棒了,我知道)
,所以这是您现在如何声明具有ctypes的变量:
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)
它告诉我我需要它是一个Python整数,而不是C长。
it tells me that I needs it to be a Python Integer, not a C long.
在这里它变得复杂,因为没有真正声明example,所以我无法执行.value方法。它将返回语法错误。我无法将example声明为python整数,因为无法做到这一点。至少,据我所知)
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)
任何帮助将不胜感激!
推荐答案
test
是一个类;创建的实例测试
代替:
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
这篇关于如何在不声明C类型的情况下将其转换为python整数? -Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!