Showing posts with label Call c# code from python. Show all posts
Showing posts with label Call c# code from python. Show all posts

Thursday, June 9, 2022

How to call C# code from Python -

Install - pip install clr

pip install --pre pythonnet

Please find the below example -


C# Code :

namespace PrintYourName

{

    [ComVisible(true)]

    public class Test

    {

        public int DoSum(int a, int b)

        {

            return a + b;

        }


        public int DoSub(int a, int b)

        {

            return a - b;

        }


        public int DoMul(int a, int b)

        {

            return a * b;

        }


        public string printName()

        {

            return "Balaji";

        }

        public static string GetZonedDateTime()

        {

            DateTime dateTime = DateTime.Now;

            string zonedDateTime = string.Format("{0:yyyy-MM-ddTHH:mm:ss.fffZ}", dateTime.ToLocalTime());

            return zonedDateTime;

        }

    }

}

Python Code:

import clr

import sys

print(sys.version)

lb = clr.AddReference(r"C:\Project\Automation\PrintYourName\obj\Debug\net6.0\PrintYourName.dll")

from C#NameSpace import ClassName

from PrintYourName import Test

# from System.IO import *

# from System.Convert import *

c= Test()

print("Addition Result is", c.DoSum(10,10))

print("Subtraction Result is", c.DoSub(12,10))

print("Multiply Result is", c.DoMul(20,10))

print("Name is ", c.printName())


Output: