Calling C# code within Python3.6

北慕城南 提交于 2021-01-21 04:49:44

问题


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# Class Library setup

I'm using the VS 2017 CE.

I create a new project TestClassLibrary under the type of ClassLibrary(.NET Standard)

The classes inside the project are as follows -

MyClass.cs

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

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

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

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'

Should the code be -

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

I get -

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 :(


回答1:


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.

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



来源:https://stackoverflow.com/questions/48082043/calling-c-sharp-code-within-python3-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!