zoukankan      html  css  js  c++  java
  • Python ctypes的byref和pointer有啥区别

    byref(n)返回的相当于C的指针右值&n,本身没有被分配空间:

    >>> from ctypes import *
    >>> n = c_int(0)
    >>> p = byref(n)
    >>> pp = byref(p)
    Traceback (most recent call last):
      File "<pyshell#4>", line 1, in <module>
        pp = byref(p)
    TypeError: byref() argument must be a ctypes instance, not 'CArgObject'

    pointer返回的相当于指针左值T* p=&n,可以改变,可以取地址:

    >>> from ctypes import *
    >>> n = c_int(0)

    >>> q = pointer(n)
    >>> q.contents = c_int(1)
    >>> qq = byref(q)
    >>> dir(qq)
    ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_obj']
    >>> type(qq)
    <class 'CArgObject'>                  #'CArgObject'是什么对象???

    >>> qq
    <cparam 'P' (010AD238)>
    >>> q
    <__main__.LP_c_long object at 0x010AD210>
    >>> q.contents
    c_long(1)

    对于T**参数,通常你得构造一个pointer,然后byref传进去

    以__开头并以__结束的属性(__class__、__dir__ 等)都是为内置方法(built-in method),唯独_obj不是

    >>> qq._obj
    <__main__.LP_c_long object at 0x010B8120>
    >>> q
    <__main__.LP_c_long object at 0x010B8120>

    由以上执行代码可知,二维指针qq的_obj属性就是该二维指针的首地址,即指向q指针的地址

    PS: addressof返回一个Python整数,不能直接传给C那边

  • 相关阅读:
    Eclipse Alt + / 无提示
    洛谷 P1101 单词方阵
    力扣题解 7th 整数反转
    力扣题解 344th 反转字符串
    力扣题解 48th 旋转图像
    力扣题解 36th 有效的数独
    力扣题解 1th 两数之和
    力扣题解 283th 移动零
    力扣题解 66th 加一
    力扣题解 350th 两个数组的交集 II
  • 原文地址:https://www.cnblogs.com/fendou-999/p/3527449.html
Copyright © 2011-2022 走看看