csharp-pythonnet

Integrate Python with C# using Python.NET

  • 3 min

Python.NET is a library that provides interoperability between Python and C# in .NET applications.

With Python.NET, we can easily invoke Python code from C#, and use Python libraries and access the resources of the Python ecosystem directly in .NET applications.

This capability is especially useful for integrating advanced Python functionalities, such as machine learning and data analysis, into applications developed with .NET.

Features of Python.NET,

  • Complete Interoperability: Allows calling Python code from C#, and vice versa, facilitating the integration of both technologies.
  • Access to Python Libraries: Enables direct use of Python libraries in .NET applications.
  • Data Type Support: Handles conversion between Python and C# data types automatically.
  • Python Script Execution: Allows executing Python scripts and using their results in C# applications.

Interoperability can have an impact on performance, especially if frequent calls are made between C# and Python. That is, don’t expect fast programs (Python is very slow, and with interop it’s even worse).

Installing Python.NET

To add Python.NET to your project, use the NuGet package manager. Open the terminal or the Visual Studio Package Manager Console and run the following command:

Install-Package Pythonnet

Alternatively, through the NuGet interface in Visual Studio, search for Pythonnet and install it in your project.

How to Use Python.NET

Initial Configuration

To start using Python.NET in your C# project, you need to initialize the Python environment and configure the Python interpreter. Here is an example of how to do it:

using Python.Runtime;

// replace with the version of Python you have installed
Runtime.PythonDLL = "python312.dll";

PythonEngine.Initialize();
using (Py.GIL())
{
    dynamic np = Py.Import("numpy");
    Console.WriteLine(np.cos(np.pi * 2));

    dynamic sin = np.sin;
    Console.WriteLine(sin(5));

    double c = (double)(np.cos(5) + sin(5));
    Console.WriteLine(c);

    dynamic a = np.array(new List<float> { 1, 2, 3 });
    Console.WriteLine(a.dtype);

    dynamic b = np.array(new List<float> { 6, 5, 4 }, dtype: np.int32);
    Console.WriteLine(b.dtype);

    Console.WriteLine(a * b);
    Console.ReadKey();
}
Copied!

In this example, we initialize the Python environment, import the NumPy library, create an array, and display its content in the console.

Calling Python Functions from C#

You can call functions defined in Python scripts from C# using Python.NET. Here is an example of how to do it:

  1. Define a function in a Python script. Create a file in the project solution, for example example.py. Put our functions there.
def add(a, b):
    return a + b
Copied!

In Visual Studio / file properties, set the “Copy to Output Directory” option to “Copy Always”.

  1. Call the function from C#: Now we can call our function by importing the module we created.
using Python.Runtime;

Runtime.PythonDLL = "python312.dll";

PythonEngine.Initialize();

using (Py.GIL()) // Acquire the GIL
{
    dynamic pyScript = Py.Import("example");
    dynamic result = pyScript.add(10, 20);
    Console.WriteLine($"Result of the addition: {result}");
}
Copied!

In this example, we import the Python script and call the add function, passing two arguments. The result is displayed in the console.