Call Python Methods from C# Easily
To call Python methods in C#, you can use the Python.NET library. It is an open-source software package that allows you to embed Python code in C# code and call Python functions and methods. Here is a simple example code demonstrating how to call Python methods in C#:
using System;
using Python.Runtime;
namespace PythonIntegration
{
class Program
{
static void Main(string[] args)
{
// 初始化Python运行时
using (Py.GIL())
{
dynamic sys = Py.Import("sys");
Console.WriteLine(sys.version);
dynamic math = Py.Import("math");
double x = math.cos(1);
Console.WriteLine(x);
}
}
}
}
In this example, we start by importing the Python.Runtime namespace, then initialize the Python runtime using Py.GIL(). Next, we import the sys and math modules and call their methods. Finally, we can print the output in the C# console.
Please note, in order for the Python.NET library to function properly, you will need to install the Python.NET NuGet package and add a reference to Python.Runtime.dll in your C# project. Additionally, you must ensure that the Python interpreter is installed on your system.