【问题标题】:Python ctypes behaviour with variable typesPython ctypes 具有变量类型的行为
【发布时间】:2020-10-19 13:36:07
【问题描述】:

我正在使用第三方 python 库,即使用 ctypes(它使用 dll)。我对ctypes不是很熟悉。该库提供了类型定义和结构定义,如下面的最小示例中所示。我正在尝试将成员变量myClassInst.MSGTYPE 分配给常量MYConst 的值。之后我想用 unittest 断言宏检查值,但由于类型不同,检查失败。下面的输出中也显示了不同的类型。

我不明白,为什么类型不同?编写那段代码的正确方法是什么?我是 Python 新手,提前感谢您的支持

from ctypes import *
import unittest

MyType  = c_ubyte
MYConst = MyType(0xED)

class MyClass (Structure):
    _fields_ = [ ("MSGTYPE", MyType) ]

class myTest(unittest.TestCase):
    def test(self):
        myClassInst = MyClass()
        myClassInst.MSGTYPE = MYConst
        print(type(MYConst))
        print(type(myClassInst.MSGTYPE))
        self.assertEqual(MYConst, myClassInst.MSGTYPE)

if __name__ == '__main__':
    unittest.main()

输出是:

<class 'ctypes.c_ubyte'>
<class 'int'>
F
======================================================================
FAIL: test (__main__.myTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "mimimumexample.py", line 16, in test
    self.assertEqual(MYConst, myClassInst.MSGTYPE)
AssertionError: c_ubyte(237) != 237

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (failures=1)

【问题讨论】:

    标签: python python-3.x ctypes


    【解决方案1】:

    在 ctypes 结构中,ctypes 在读取/写入成员变量时“有效地”转换为 Python 对象/从 Python 对象转换,因此读取 MYConst 会生成 Python int。

    MYConst = MyType(0xED)改成MyConst = 0xED就可以正常工作了。

    (感谢您提供带有单元测试的独立示例!)

    【讨论】:

    • 不客气。对我来说,最少的独立示例非常重要。在 C++-World 中,我什至添加了在线编译器链接,但我在 stackoverflow.com/questions/64428629/… 上关于 Python 在线编译器的友好问题已立即关闭。在堆栈溢出时变得很难......
    • 不幸的是,常量也是库的一部分。我无法改变它。但是,尽管如此,答案有助于理解问题。类 ctypes._SimpleCData.value 属性有助于从常量返回 python int。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多