pythonc#visual-studiopython.net

Python.NET Initialize throws MissingMethodException


I need to use python code from my C#/.NET software. I've been trying to use Python.NET for that: installed the pythonnet nuget package in visual studio (version 3.0.1) and first trying to load some example code from a test file (a basic method to add two numbers) like this:

using Python.Runtime;

private void TestMethod()
{ 
  PythonEngine.Initialize();
  using (Py.GIL())
  {
    dynamic pythonModule = Py.Import("c_sharp_test");
    dynamic pythonClass = pythonModule.NumberAdder;
    dynamic instance = pythonClass();
    dynamic result = instance.add_numbers(3.14, 2.5);
    double number = (double)result;
  }
  PythonEngine.Shutdown();
}

But the execution doesn't even go beyond the PythonEngine.Initialize() - I get a MissingMethodException with the message "Failed to load symbol Py_IncRef." I tried reinstalling python, verified that it's installed correctly - I can run python scripts normally (using version 3.11.3), the assembly reference has been added when I installed the nuget package, I added the environment variables PATH pointing to the python installation folder, PYTHONHOME, also pointing there, and PYTHONPATH pointing to <python_directory>\Lib\site-packages but nothing helped.

Advice would be much appreciated.


Solution

  • I think you should set Runtime.PythonDLL before PythonEngine.Initialize(); as Runtime.PythonDLL = "python311.dll";

    In your code it would look like:

    using Python.Runtime;
    
    private void TestMethod()
    { 
      Runtime.PythonDLL = "python311.dll";
      PythonEngine.Initialize();
      using (Py.GIL())
      {
         dynamic pythonModule = Py.Import("c_sharp_test");
         dynamic pythonClass = pythonModule.NumberAdder;
         dynamic instance = pythonClass();
         dynamic result = instance.add_numbers(3.14, 2.5);
         double number = (double)result;
       }
       PythonEngine.Shutdown();
    }
    

    You can find this information in the Pythonnet documentation under "Embedding Python in .NET"