【问题标题】:Python import dllPython 导入 dll
【发布时间】:2011-07-12 08:24:23
【问题描述】:

如何将 winDLL 导入 python 并使用它的所有功能?它只需要双精度和字符串。

【问题讨论】:

标签: python dll ctypes


【解决方案1】:

您已标记问题ctypes,因此听起来您已经知道答案了。

ctypes tutorial 非常棒。一旦您阅读并理解,您将能够轻松地做到这一点。

例如:

>>> from ctypes import *
>>> windll.kernel32.GetModuleHandleW(0)
486539264

还有一个来自我自己代码的例子:

lib = ctypes.WinDLL('mylibrary.dll')
#lib = ctypes.WinDLL('full/path/to/mylibrary.dll')
func = lib['myFunc']#my func is double myFunc(double);
func.restype = ctypes.c_double
value = func(ctypes.c_double(42.0))

【讨论】:

  • 好吧,我知道我需要 ctypes 但我不知道如何使用它们。 :) 另外,非常好的链接! python文档似乎只适合参考,而不是实际学习。非常感谢!
  • 等等!我想我忽略了你的代码。看了教程,好像只是演示了如何加载windows DLLs。我需要加载一个自定义 DLL 文件。我该怎么做?
  • @Patrick 我添加了另一个示例。但这一切都在教程中。调用您自己的 DLL 和 Windows DLL 之间没有理论上的区别。
  • 我不想再打扰你了......但是你能检查一下我在原始问题中输入的代码吗?谢谢!
  • @Patrick 请你简单地问一个新问题。包括代码,包括 ctypes 代码和 DLL 函数签名。
【解决方案2】:

我正在发布我的经验。首先,尽管我费了很大力气把所有部分放在一起,但导入 C# dll 很容易。我的做法是:

1) 安装此 nuget 包(我不是所有者,只是非常有用)以构建非托管 dll:https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports

2) 你的 C# dll 代码是这样的:

using System;
using RGiesecke.DllExport;
using System.Runtime.InteropServices;

public class MyClassName
{
   [DllExport("MyFunctionName",CallingConvention = CallingConvention.Cdecl)]
   [return: MarshalAs(UnmanagedType.LPWStr)]
   public static string MyFunctionName([MarshalAs(UnmanagedType.LPWStr)] string iString)
   {
       return "hello world i'm " + iString
   }
}

3) 你的python代码是这样的:

import ctypes
#Here you load the dll into python 
MyDllObject = ctypes.cdll.LoadLibrary("C:\\My\\Path\\To\\MyDLL.dll")
#it's important to assing the function to an object
MyFunctionObject = MyDllObject.MyFunctionName
#define the types that your C# function return
MyFunctionObject.restype = ctypes.c_wchar_p
#define the types that your C# function will use as arguments
MyFunctionObject.argtypes = [ctypes.c_wchar_p]
#That's it now you can test it
print(MyFunctionObject("Python Message"))

【讨论】:

    【解决方案3】:

    c-types 注意!

    使用WinDLL(和wintypesmsvcrt)是特定于Windows 的导入,并不总是有效,即使在Windows 上也是如此!原因是它取决于您的 python 安装。是原生 Windows(还是使用 Cygwin 或 WSL)?

    对于ctypes,更便携和正确的方法是像这样使用cdll

    import sys
    import ctypes
    from ctypes import cdll, c_ulong
    
    kFile = 'C:\\Windows\\System32\\kernel32.dll'
    mFile = 'C:\\Windows\\System32\\msvcrt.dll'
    
    try: 
        k32    = cdll.LoadLibrary(kFile)
        msvcrt = cdll.LoadLibrary(mFile)
    except OSError as e:
        print("ERROR: %s" % e)
        sys.exit(1)
    
    # do something...
    

    【讨论】:

      【解决方案4】:

      使用Cython,既可以访问 DLL,也可以为它们生成 Python 绑定。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-15
        • 2016-01-22
        • 1970-01-01
        • 1970-01-01
        • 2011-05-03
        • 2018-08-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多