gpt4 book ai didi

c# - Python3.6内调用C#代码

转载 作者:行者123 更新时间:2023-12-03 14:57:39 28 4
gpt4 key购买 nike

在完全不了解 C# 编码的情况下,我希望在我的 python 代码中调用 C# 函数。我知道围绕同一个问题有很多问答,但出于某种奇怪的原因,我无法从示例 python 模块中导入简单的 c# 类库。

以下是我所做的 -

C# Class Library setup



我正在使用 VS 2017 CE。

我创建了一个新项目 TestClassLibraryClassLibrary(.NET Standard) 的类型下

项目内的类如下——

MyClass.cs
using System;
namespace TestClassLibrary
{
public class MyClass
{
public string function()
{
return "Hello World!";
}
}
}

这已成功构建,生成 .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

当我运行 python main.py ,代码失败并出现错误 -
Traceback (most recent call last):
File "main.py", line 6, in <module>
from TestClassLibrary import MyClass
ModuleNotFoundError: No module named 'TestClassLibrary'

代码应该是 -
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

我得到 -
clr.AddReference("TestClassLibrary.dll")
System.IO.FileNotFoundException: Unable to find assembly 'TestClassLibrary.dll'.
at Python.Runtime.CLRModule.AddReference(String name)

但是当我运行下面的代码时,代码按预期运行 -
import clr
clr.AddReference(r"System.Windows.Forms")
from System.Windows.Forms import MessageBox
MessageBox.Show("Hello World!")

我不知道我可能会错过什么:(

最佳答案

这真的很笨拙,但我喜欢做个人项目的事情。
Python 让您可以非常轻松地将内容发送到命令行。 C# 可以从命令行运行。你可能会看到我要去哪里。
尝试将升 C 添加到 PATH。将操作系统导入 python。然后在要运行 C# 脚本时使用这行代码:

os.system("csc nameofscript.cs")
也许我误解了,但这就是我如何让它在我的机器上工作

关于c# - Python3.6内调用C#代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48082043/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com