通过pythonn使用Python中的C#程序集

2024-10-03 23:24:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我用的是Windows7,64位。我已经下载并安装了pythonnet,所以

import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import Form

工作正常。我还下载并编译/运行了一个C#应用程序,它创建了许多程序集。所讨论的应用程序是ARDrone Control-.NET。

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

因为我从来没有使用过C#(这就是为什么我想使用Python中的库),所以我很乐意澄清这个问题。


Tags: fromimport程序form应用程序netwindowsforms
2条回答

据我所知,您正试图在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'>

只是提供另一种方法:

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

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

MyClass.does_something()

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

所以“诀窍”是必须在clr.AddReference之前将assemblies文件夹添加到sys.path

相关问题 更多 >