【问题标题】:Calling DLL function in Python在 Python 中调用 DLL 函数
【发布时间】:2013-08-01 16:21:27
【问题描述】:

我无法理解如何从 Python 中的现有 dll 调用 dll 函数。

OTAClient = cdll.LoadLibrary("C:\PATH\OTAClient.dll")
connect = OTAClientDLL.TDConnection()

exceptions.AttributeError: function 'TDConnection' not found                

我读到了一些名称被编译器破坏的东西。 有什么建议吗?

【问题讨论】:

    标签: python dll ctypes


    【解决方案1】:

    DLL 实际上是一个 COM DLL。 需要 comtypes 才能使用这种类型的 DLL 而不是 ctypes。 确保download comtypes

    from comtypes.client import CreateObject
    
    OTAClientDLL = comtypes.client.GetModule("C:\PATH\OTAClient.dll")
    

    【讨论】:

      【解决方案2】:

      这可能是因为编译器修改了函数名。有两种方法可以解决这个问题:

      1. 修复代码以告诉编译器不要破坏名称。 (查找添加外部引用)
      2. 找到损坏的名称并从 python 调用它(参见下面的描述)

      阅读以下内容(来自http://docs.python.org/2/library/ctypes.html

      有时,dll 导出名称不是有效 Python 标识符的函数,例如“??2@YAPAXI@Z”。在这种情况下,您必须使用 getattr() 来检索函数:

      >>>
      >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") 
      <_FuncPtr object at 0x...>
      >>>
      

      在 Windows 上,某些 dll 不是按名称而是按序号导出函数。可以通过使用序号索引 dll 对象来访问这些函数:

      >>>
      >>> cdll.kernel32[1] 
      <_FuncPtr object at 0x...>
      >>> cdll.kernel32[0] 
      Traceback (most recent call last):
        File "<stdin>", line 1, in ?
        File "ctypes.py", line 310, in __getitem__
          func = _StdcallFuncPtr(name, self)
      AttributeError: function ordinal 0 not found
      >>>
      

      如果您不确定函数名称可能是什么,请查找 link.exe dumpbin.exe。这些可以在 Visual Studio 安装中找到,它们会转储 dll 中可用的所有功能。您可以对结果运行 grep。

      【讨论】:

      • 我之前查看过这个文档,这没有帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 1970-01-01
      • 2013-11-25
      • 1970-01-01
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多