Python 导入 DLL
我该如何把一个winDLL导入到Python中,并且能够使用它的所有功能?我只需要处理双精度浮点数和字符串。
5 个回答
3
c-types 注意事项!
使用 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...
3
我想分享一下我的经验。首先,尽管我花了很多力气把所有的部分都拼凑在一起,但导入一个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"))
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))