Calling C# code within Python3.6

5.8k views Asked by At

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

There are 1 answers

0
Matt On

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