【发布时间】:2011-07-12 08:24:23
【问题描述】:
如何将 winDLL 导入 python 并使用它的所有功能?它只需要双精度和字符串。
【问题讨论】:
-
到目前为止你有什么,它怎么不工作?
如何将 winDLL 导入 python 并使用它的所有功能?它只需要双精度和字符串。
【问题讨论】:
您已标记问题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))
【讨论】:
我正在发布我的经验。首先,尽管我费了很大力气把所有部分放在一起,但导入 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"))
【讨论】:
使用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...
【讨论】:
使用Cython,既可以访问 DLL,也可以为它们生成 Python 绑定。
【讨论】: