Ska*_*ani 7 .net c# python python.net pythonnet
由于完全不了解 C# 中的编码,我希望在我的 python 代码中调用一个 C# 函数。我知道围绕同一问题有很多问答,但由于某些奇怪的原因,我无法从示例 python 模块导入一个简单的 c# 类库。
以下是我所做的 -
C# 类库设置
我正在使用 VS 2017 CE。
我TestClassLibrary
在以下类型下创建了一个新项目ClassLibrary(.NET Standard)
项目内部的类如下——
MyClass.cs
using System;
namespace TestClassLibrary
{
public class MyClass
{
public string function()
{
return "Hello World!";
}
}
}
Run Code Online (Sandbox Code Playgroud)
这已成功构建,在.dll
目录下生成文件\bin\Debug\netstandard2.0
为TestClassLibrary.dll
现在,我切换到 python3.6(在 virtualenv 上运行,支持 pythonnet 2.3.0)
主文件
import sys
sys.path.append(r"<Ablsloute Path to \bin>\Debug\netstandard2.0")
import clr
clr.AddReference(r"TestClassLibrary")
from TestClassLibrary import MyClass
Run Code Online (Sandbox Code Playgroud)
当我运行时python main.py
,代码失败并出现错误 -
Traceback (most recent call last):
File "main.py", line 6, in <module>
from TestClassLibrary import MyClass
ModuleNotFoundError: No module named 'TestClassLibrary'
Run Code Online (Sandbox Code Playgroud)
代码应该是 -
import sys
sys.path.append(r"C:\Users\DELL\source\repos\TestClassLibrary\TestClassLibrary\bin\Debug\netstandard2.0")
import clr
clr.AddReference("TestClassLibrary.dll")
from TestClassLibrary import MyClass
Run Code Online (Sandbox Code Playgroud)
我明白了——
clr.AddReference("TestClassLibrary.dll")
System.IO.FileNotFoundException: Unable to find assembly 'TestClassLibrary.dll'.
at Python.Runtime.CLRModule.AddReference(String name)
Run Code Online (Sandbox Code Playgroud)
但是当我运行下面的代码时,代码按预期运行 -
import clr
clr.AddReference(r"System.Windows.Forms")
from System.Windows.Forms import MessageBox
MessageBox.Show("Hello World!")
Run Code Online (Sandbox Code Playgroud)
我不知道我可能会错过什么:(
这真的很糟糕,但我多么喜欢做个人项目的事情。Python 可以让您非常轻松地将内容发送到命令行。C# 可以从命令行运行。你可能明白我的意思了。
尝试将 C Sharp 添加到 PATH。将操作系统导入到 python 中。然后当您想要运行 C# 脚本时使用这行代码:
os.system("csc nameofscript.cs")
Run Code Online (Sandbox Code Playgroud)
也许我误解了,但这就是我让它在我的机器上工作的方式