Python导入dll

问题描述 投票:0回答:5

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

python dll ctypes
5个回答
21
投票

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

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

例如:

>>> 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))

3
投票

我正在发布我的经验。首先,尽管我付出了很多艰苦的工作才能将所有部分组合在一起,但导入 C# dll 很容易。我的做法是:

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

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 型注意!

使用

WinDLL
(和
wintypes
msvcrt
)是 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...

1
投票

使用 Cython 来访问 DLL,并为它们生成 Python 绑定。


0
投票

将 dll 文件保留在“C:\Windows”位置的 System32 或 SysWOW64 文件夹中。使用 python

ctypes
cffi
库。如果您使用 cffi 库:

from cffi import FFI
ffi = FFI()
ffi.dlopen("kernel32")
ffi.dlopen("msvcrt")
ffi.dlopen("MyDLL")
ffiobj = ffi.dlopen('MyDLL2')

或者

import ctypes
kernel_32 = ctypes.WinDLL('kernel32')

这对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.