Hits

Last updated: October 7, 2023;

There might be situations where the need arises to seamlessly incorporate Python functionality within a C# project. For instance, recently, I encountered a scenario where I had to test a third-party Python algorithm within our company’s existing C# application. Translating the Python algorithm into native C# would have been time-consuming, so I set out to find an integration solution for a quick test. This use case may resonate with you, and there’s another common situation where a Python library might not have native support within the .NET environment.

In both of these scenarios, having a convenient method to test Python code within your C# project can prove incredibly useful. In this blog post, I’ll share a straightforward approach I discovered for achieving this. I’ve included step-by-step instructions complete with screenshots, though I should note that I conducted this on a Windows (x64) machine. The process may vary for Linux or Mac users, but the principles remain the same.

Let’s dive in!

Table of contents

  1. Installing Python
    A. Download Python
    B. Add to path
    C. Configure optional features
    D. Configure advanced features
    E. Complete setup
    F. Confirm Python version
    G. Install Python.Net package
    H. Confirm Python directory
  2. Creating C# project
    A. Start Visual Studio
    B. Choose “Console App (.NET Framework)”
    C. Name a project
    D. Add reference to project
    E. Browse reference
    F. Add .dll file
    G. Updated .dll file
    H. Confirm .dll file
    I. Reproduce simple code
    J. Platform error
    K. Go to “Configuration Manager”
    L. Configure platform
    M. Choose x64 platform
    N. Numpy error
    O. Install numpy
    P. Run the project
  3. Notes

1. Installing Python

A) Download Python | Install Python 3.8 from https://www.python.org/downloads/release/python-380/ (Web-based installer, respective configuration)

B) Add to path | Choose custom installation and tick “add to PATH”

C) Configure optional features | Choose all in “Optional Features”

D) Configure advanced features | Choose all in “Advanced Features”

E) Complete setup | Close window after “Setup was successful”

F) Confirm Python version | After installation, we can confirm newly installed Python by typing python --version command in “cmd”

G) Install Python.Net package | Further, we need to install Python.Net to integrate Python into our C# project. It can be done by typing pip install pythonnet. After package installation, we can optionally upgrade pip: python -m pip install --upgrade pip

H) Confirm Python directory | We can also confirm newly installed Python from the directory in File Explorer (respective install location)

2. Creating C# project

A) Start Visual Studio | Open Visual Studio 2022 and “Create a new project”

B) Choose “Console App (.NET Framework)”

C) Name a project | Give a project name and press “Create”

D) Add reference to project | In the newly created project, in the Solution Explorer, click on “References → Add reference”

E) Browse reference | In Reference Manager, go to “Browse” section and click “Browse”

F) Add .dll file | Add “Python.Runtime.dll” file. Its location should be inside installed inside Python’s pythonnet package. For example, in my case, it was inside C:/Program Files/Python38/Lib/site-packages/pythonnet/runtime

G) Updated .dll file | We should see, newly appeared “dll” file. Click “OK”

H) Confirm .dll fie | Newly appeared “Python.Runtime” in References of Solution Explorer

I) Reproduce this simple code

static void Main(string[] args)
{
    ////// This part is important!
    string pythonDll = @"C:\Python38\python38.dll"; // -> this path is where Python installed
    Environment.SetEnvironmentVariable("PYTHONNET_PYDLL", pythonDll);
    //////

    PythonEngine.Initialize();
    using (Py.GIL())  // Acquire the Python Global Interpreter Lock
    {
        dynamic np = Py.Import("numpy"); // Import the numpy module
        dynamic result = np.sqrt(4);     // Call the numpy.sqrt() function
        Console.WriteLine(result);       // Print the result
    }

    PythonEngine.Shutdown();
    Console.ReadKey();
}

J) Platform error | Run the project, if such an error appears

K) Go to “Configuration Manager”

L) Configure platform | Go to “Platform → New”

M) Choose x64 platform | Choose “x64 → OK” from New platform

N) Numpy error | Run the project, if such an error appears

O) Install numpy | In “cmd” terminal, type pip install numpy --user to install NumPy package

P) Run the project | Run the project again, if everything worked, the terminal console should return 2.

Notes

  1. conda does not work with pythonnet. I could not catch outputs, terminal turns off quickly
  2. Python.Net works with python>=3.6 and python<=3.8. Higher or lower version could cause issues (as of 2023/08)