通过pythonnet使用Python的C#程序集

Pet*_*ter 8 .net python python.net

我使用的是Windows 7,64位.我已经设法下载并安装了pythonnet,所以

import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import Form
Run Code Online (Sandbox Code Playgroud)

工作良好.我还下载并编译/运行了一个创建大量程序集的C#应用​​程序.有问题的应用程序是ARDrone-Control-.NET.

我如何使用Python生成的DLL文件(而不仅仅是内置的C#类).

由于我从未使用过C#(这就是为什么我想使用Python中的库),我很乐意澄清这个问题.

Joh*_*ohn 12

只是提供另一种方法:

import sys
sys.path.append("C:\Path\to\your\assemblies")

clr.AddReference('MyAssembly')
from MyAssembly import MyClass

MyClass.does_something()
Run Code Online (Sandbox Code Playgroud)

这假定在C:\Path\to\your\assemblies文件夹中有一个MyAssembly.dll文件.

所以'技巧'是你必须将程序集文件夹添加到sys.path之前clr.AddReference.


mit*_*lsg 3

据我所知,您正在尝试在 Python.Net 中加载外部程序集,我对该库做了很少的工作。您应该考虑使用 IronPython,但使用 Python.Net 您可以通过 .Net 的反射加载程序集,如下所示

Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import clr
>>> from System.Reflection import Assembly
>>> dll1 = Assembly.LoadFile("C:\Python\Python27-32\Lib\site-packages\Python.Runtime.dll")
>>> clr.Python.Runtime
<module 'Python.Runtime'>
>>> clr.Python.Runtime.PythonEngine
<class 'Python.Runtime.PythonEngine'>
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,IronPython 不是一个选项,因为大量其他扩展包仅适用于 CPython。 (2认同)