Calling C# code within Python3.6

2024/10/8 12:39:55

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

Answer

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://en.xdnf.cn/q/70120.html

Related Q&A

Pycharm 3.4.1 - AppRegistryNotReady: Models arent loaded yet. Django Rest framewrok

Im using DRF and Pycharm 3.4.1 and Django 1.7. When I try to test my serializer class via Pycharm django console, it gives me the following error:Codefrom items_app.serializers import ItemSerializer s …

Pass Flask route parameters into a decorator

I have written a decorator that attempts to check we have post data for a Flask POST route:Heres my decorator:def require_post_data(required_fields=None):def decorator(f):@wraps(f)def decorated_functio…

update env variable on notebook in VsCode

I’m working on a python project with a notebook and .env file on VsCode. I have problem when trying to refresh environment variables in a notebook (I found a way but its super tricky). My project: .en…

How do I properly set up flask-admin views with using an application factory?

Im trying to setup flask-admin model views with SQLAlchemy against user and role models. Instead of a function admin view Im getting:ValueError: Invalid model property name <class app.models.Role>…

Django Rest Framework: Correct way to serialize ListFields

Based on the DRF documentation I have a created a list of email_id stored in my model in the following way Models.pyclass UserData(models.Model):emails = models.CharField(max_length=100,blank=False)In…

Flask-SQLAlchemy TimeoutError

My backend configuration is :Ubuntu 12.04 Python 2.7 Flask 0.9 Flask-SQLAlchemy Postgres 9.2Ive got this error message: TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed ou…

Making saxon-c available in Python

I have just read that Saxon is now available for Python, and thats just great fun and good, but can anyone write a tutorial on how to make it available for Python/Anaconda/WingIDE or similar? I am use…

How to include multiple interactive widgets in the same cell in Jupyter notebook

My goal is to have one cell in Jupyter notebook displaying multiple interactive widgets. Specifically, I would like to have four slider for cropping an image and then another separate slider for rotati…

SWIG - Problem with namespaces

Im having trouble getting the following simple example to work with SWIG 1.3.40 (and I also tried 1.3.31). The Foo structure comes through as a Python module as long as I dont wrap it in a namespace, b…

Django access to subclasses items from abstract class

class Animal(models.Model):....class Meta:abstract = Trueclass Cat(models.Model, Animal):...class Dog(models.Model, Animal):....I want to be able to return all instances of querysets of all the subclas…