在Python3.6中调用C#代码 [英] Calling C# code within Python3.6

查看:90
本文介绍了在Python3.6中调用C#代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全不懂C#编码,所以我想在我的python代码中调用C#函数.我知道有很多关于相同问题的问答,但是由于某些奇怪的原因,我无法从示例python模块导入简单的c#类库.

with absolutely no knowledge of coding in C#, I wish to call a C# function within my python code. I know there's quite a lot of Q&As around the same problem, but for some strange reason, i'm unable to import a simple c# class library from a sample python module.

以下是关于我所做的事情-

Here's below as to what i've done -

C#类库设置

我正在使用VS 2017 CE.

I'm using the VS 2017 CE.

我以 ClassLibrary(.NET Standard)

项目内部的类如下-

MyClass.cs

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

这已成功构建,并在 \ bin \ Debug \ netstandard2.0 目录下以 TestClassLibrary.dll

This was built successfully, generating the .dll file under the \bin\Debug\netstandard2.0 dir as TestClassLibrary.dll

现在,我切换到python3.6(在以pythonnet 2.3.0为后盾的virtualenv上运行)

Now, I switch over to python3.6 (running on a virtualenv, backed with pythonnet 2.3.0)

main.py

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 时,代码失败并显示错误-

When i Run python main.py, the code fails with the error -

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)

但是当我运行下面的代码时,代码按预期运行-

But when i ran the code below, the code runs as expected -

import clr
clr.AddReference(r"System.Windows.Forms")
from System.Windows.Forms import MessageBox
MessageBox.Show("Hello World!")

我不知道我可能会缺少什么:(

I've no idea of what i might be missing :(

推荐答案

这确实很麻烦,但是我喜欢做属于个人项目的事情.Python使您可以非常轻松地将内容发送到命令行.可以从命令行运行C#.您可能会看到我要去的地方.

This is really janky but how I like to do things that are personal projects. Python lets you send stuff to the command line really easily. C# can be run from command line. You probably see where I'm going with this.

尝试将C Sharp添加到PATH.将os导入python.然后在要运行C#脚本时使用以下代码:

Try adding C sharp to PATH. import os to python. then use this line of code when you want to run the C# script:

os.system("csc nameofscript.cs")

也许我误会了,但这就是我要使其在我的机器上工作的方式

perhaps I've misunderstood, but this is how I would make it work on my machine

这篇关于在Python3.6中调用C#代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆