How to call a Python function from C#
An interface must be built between two programming languages to communicate and exchange information seamlessly.
It supports the software's modularity, reusability, and maintainability. It also enables integrating various systems, components, or programming languages.
Programmers can implement interfaces in various ways, such as libraries, frameworks, or application programming interfaces (APIs), which offer a standard set of interfaces for communication components. In addition, some programming languages have built-in functionality for interacting with other dialects or platforms. For instance, the ctypes module in Python enables calling C functions from Python.
To call a Python function from C#, we'll use the Python.NET library. This package allows us to integrate Python with .NET projects and applications, enabling us to use the Python libraries within a .NET application, e.g., C# or any other .NET language.
Steps
1. Installation
The Python.NET library can be installed using the NuGet package manager in Visual Studio.
The first thing to do is to open Visual Studio and create a new project.
Right-click the project name and select "Manage NuGet Packages" in the solutions explorer.
Select the "browse" tab within the "NuGet Package manager" window.
Search for "pythonnet" in the search box.
A list of results pops up, select Python.NET and install it.
Complete the installation.
Once the installation is complete, we can start using Python.NET in our project by importingPython.Runtimenamespace.
Another method we can use is downloading NuGet from the official website.
2. Create a Python script
We'll save the Python script with a name of our liking. We can save it as multiply_numbers.py and add the function we want to call from C#.
def multiply_numbers(x, y, z):return x * y * z
In the code above:
Line 1: We declare a function with the name
multiply_numbers(). This function receives 3 parameters x, y and z.Line 2: The function returns a multiplication of the 3 parameters passed to it.
3. Load the Python script
Back into our C# application, we can now load the Python script that we wrote earlier using the PythonEngine class which is obtained from the .NET library, after it has been installed.
using Python.Runtime;// Initialize the Python enginePythonEngine.Initialize();// Load the Python scriptdynamic multiplyNumbersModule = PythonEngine.ModuleFromString("multiply_numbers", File.ReadAllText("multiply_numbers.py"));
Explanation
Line 1: This block of code imports the
Python.Runtimenamespace. This namespace contains all the methods and classes which is needed to work with Python codes from within a C# application using the .NET library.Line 4: We initialize the
PythonEngineclass from C#. This method initializes the Python runtime environment provided by Python for .NET library, which means that thePythonEngineclass is used to interact with the Python runtime environment. It is also important to know that thePythonEngine.Initialize()class must be called just once per application instance.Line 7: The dynamic keyword in C# indicates that the type of the variable will be determined at runtime. Next, we create a new module from the first argument with the name
multiply_numbers. Lastly, theFile.ReadAllText()method read all the content from the script filemultiply_numbers.py.
4. Call Python function
We call our Python function from C# using the dynamic object that was created in the previous step of this tutorial.
// We call the Python functiondynamic output = multiplyNumbersModule.multiply_numbers(1, 2, 3);// Print the resule in the console.Console.WriteLine(output); // Output: 6
Explanation
Line 2: From the previously created module (
multiplyNumbersModule) that takes three arguments, we call themultiply_numbersfunction by passing the three arguments1,2, and3. The result of the function is returned as a Python object.Line 5: We print the result to the console.
Conclusion
Additionally, the Python.NET library provides access to some data analysis and machine learning libraries in Python such as NumPy, pandas and of course scikit-learn.
This makes it possible to take advantage of the rich scientific computing and data analysis capabilities of Python in your .NET application.
Free Resources