Python ctypes中cast/py_object用法

class ctypes.py_object

Represents the C PyObject * datatype. Calling this without an argument creates a NULL PyObject * pointer.

示例:

>>> dc = {‘a‘:‘aaa‘,‘b‘:‘bbb‘}

>>> c = py_object(dc)
>>> c
py_object({‘b‘: ‘bbb‘, ‘a‘: ‘aaa‘})
>>> c.value
{‘b‘: ‘bbb‘, ‘a‘: ‘aaa‘}
>>> dc
{‘b‘: ‘bbb‘, ‘a‘: ‘aaa‘}

Type conversions

Usually, ctypes does strict type checking. This means, if you have POINTER(c_int) in the argtypes list of a function or as the type of a member field in a structure definition, only instances of exactly the same type are accepted. There are some exceptions to this rule, where ctypes accepts other objects. For example, you can pass compatible array instances instead of pointer types. So, for POINTER(c_int), ctypes accepts an array of c_int:

>>>

>>> class Bar(Structure):
...     _fields_ = [("count", c_int), ("values", POINTER(c_int))]
...
>>> bar = Bar()
>>> bar.values = (c_int * 3)(1, 2, 3)
>>> bar.count = 3
>>> for i in range(bar.count):
...     print(bar.values[i])
...
1
2
3
>>>

In addition, if a function argument is explicitly declared to be a pointer type (such as POINTER(c_int)) in argtypes, an object of the pointed type (c_int in this case) can be passed to the function. ctypes will apply the required byref() conversion in this case automatically.

To set a POINTER type field to NULL, you can assign None:

>>>

>>> bar.values = None
>>>

Sometimes you have instances of incompatible types. In C, you can cast one type into another type. ctypes provides a cast() function which can be used in the same way. The Bar structure defined above accepts POINTER(c_int) pointers or c_int arrays for its values field, but not instances of other types:

>>>

>>> bar.values = (c_byte * 4)()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
>>>

For these cases, the cast() function is handy.

The cast() function can be used to cast a ctypes instance into a pointer to a different ctypes data type. cast() takes two parameters, a ctypes object that is or can be converted to a pointer of some kind, and a ctypes pointer type. It returns an instance of the second argument, which references the same memory block as the first argument:

>>>

>>> a = (c_byte * 4)()
>>> cast(a, POINTER(c_int))
<ctypes.LP_c_long object at ...>
>>>

So, cast() can be used to assign to the values field of Bar the structure:

>>>

>>> bar = Bar()
>>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
>>> print(bar.values[0])
0
>>>

Python ctypes中cast/py_object用法

时间: 2024-10-10 01:30:36

Python ctypes中cast/py_object用法的相关文章

几招学会 Python 3 中 PyMongo 的用法

本文和大家分享的是Python3下MongoDB的存储操作相关内容,在看本文之前请确保你已经安装好了MongoDB并启动了其服务,另外安装好了Python的PyMongo库.下面进入正题,一起来看看吧,希望对大家学习Python3有所帮助. 连接MongoDB 连接MongoDB我们需要使用PyMongo库里面的MongoClient,一般来说传入MongoDB的IP及端口即可,第一个参数为地址host,第二个参数为端口port,端口如果不传默认是27017. import pymongo cl

python numpty 中shape的用法

python: numpy--函数 shape用法 - CSDN博客 https://blog.csdn.net/u010758410/article/details/71554224 shape函数是numpy.core.fromnumeric中的函数,它的功能是查看矩阵或者数组的维数. 举例说明: 建立一个3×3的单位矩阵e, e.shape为(3,3),表示3行3列,第一维的长度为3,第二维的长度也为3 [plain] view plain copy >>> e = eye(3)

python matplotlib 中ax.legend()用法解释

ax.legend()作用:在图上标明一个图例,用于说明每条曲线的文字显示 import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in range(5): #ax.plot(x, i * x, label='y=%dx' %i) ax.plot(x, i * x, label='$y = %ix$' % i) ax.le

python scapy中sniffer的用法以及过滤器

Sniff方法定义: sniff(filter="",iface="any", prn=function, count=N) 1.filter的规则使用 Berkeley Packet Filter (BPF)语法,具体参考:http://blog.csdn.net/qwertyupoiuytr/article/details/54670477 2.iface用来指定要在哪个网络接口上进行抓包[即网卡的名称](通常不指定即所有网络接口):例如: dpkg = sni

python中enumerate()的用法

先出一个题目:1.有一 list= [1, 2, 3, 4, 5, 6]  请打印输出:0, 1 1, 2 2, 3 3, 4 4, 5 5, 6 打印输出, 2.将 list 倒序成 [6, 5, 4, 3, 2, 1] 3.将a 中的偶数挑出 *2 ,结果为 [4, 8, 12] 这个例子用到了python中enumerate的用法.顺便说一下enumerate在for循环中得到计数的用法,enumerate参数为可遍历的变量,如 字符串,列表等: 返回值为enumerate类. 示例代码如

Python中range的用法

Python中range的用法 函数原型:range(start, end, scan): 参数含义:start:计数从start开始.默认是从0开始.例如range(5)等价于range(0, 5); end:技术到end结束,但不包括end.例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5 scan:每次跳跃的间距,默认为1.例如:range(0, 5) 等价于 range(0, 5, 1)

python中MySQLdb模块用法实例

篇文章主要介绍了python中MySQLdb模块用法,以实例形式详细讲述了MySQLdb模块针对MySQL数据库的各种常见操作方法,非常具有实用价值,需要的朋友可以参考下 本文实例讲述了python中MySQLdb模块用法.分享给大家供大家参考.具体用法分析如下: MySQLdb其实有点像php或asp中连接数据库的一个模式了,只是MySQLdb是针对mysql连接了接口,我们可以在python中连接MySQLdb来实现数据的各种操作. python连接mysql的方案有oursql.PyMyS

Python中assert的用法

Python中assert的用法 Python中assert用来判断语句的真假,如果为假的话将触发AssertionError错误 如: >>> a = 23 >>> a 23 >>> assert a == 23 >>> a -=1 >>> a 22 >>> assert a == 23 Traceback (most recent call last):   File "",

python 中 print 函数用法总结

Python 思想: “一切都是对象!” 在 Python 3 中接触的第一个很大的差异就是缩进是作为语法的一部分,这和C++等其他语言确实很不一样,所以要小心 ,其中python3和python2中print的用法有很多不同,python3中需要使用括号 缩进要使用4个空格(这不是必须的,但你最好这么做),缩进表示一个代码块的开始,非缩进表示一个代码的结束.没有明确的大括号.中括号.或者关键字.这意味着空白很重要,而且必须要是一致的.第一个没有缩进的行标记了代码块,意思是指函数,if 语句.