通过pythonnet在Python中使用C#程序集
我现在在用Windows 7,64位系统。我已经成功下载并安装了pythonnet,所以
import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import Form
运行得很好。我还下载并编译运行了一个C#应用程序,这个程序会生成很多的程序集。这个应用程序叫做ARDrone-Control-.NET。
我想知道如何在Python中使用这些生成的DLL文件,而不仅仅是使用内置的C#类。
因为我从来没有用过C#(这也是我想在Python中使用这个库的原因),所以如果有需要,我可以进一步解释这个问题。
2 个回答
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'>
13
这里提供另一种方法:
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
之前,你需要把你的程序集文件夹添加到 sys.path
中。