Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up pythonnet for .net using NuGet

Tags:

python.net

Iam trying to develop a simple calculator program embeddeding python in .net,I wanna reference pythonnet from NuGet to include it in my project

I installed pythonnet v2.3.0 using NuGet,I also have python 3 installed in my system

It would be nice if some one give me step by step instruction to embedd python net

form1.cs code :

using System;
...
using Python.Runtime;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
            PythonEngine.Initialize();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            int num1 = int.Parse(a.Text);
            int num2 = int.Parse(b.Text);
            result.Text = (num1 + num2).ToString();
            using (Py.GIL())
            {
                dynamic np = Py.Import("numpy");
            }
        }
     }
}

When I use using(Py.GIL()) line in my code it compiler shows

System.BadImageFormatException: 'Could not load file or assembly 'Python.Runtime, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.'

like image 914
Maghil vannan Avatar asked Sep 02 '25 15:09

Maghil vannan


2 Answers

This issue is likely caused by architecture (32-bit/64-bit) mismatch between Python.Runtime.dll and your Python.

pythonnet 2.3.0 NuGet packages currently published on nuget.org include two versions of the Python.Runtime.dll assembly: 32-bit(x86) and 64-bit(x64). There is a known issue with this package not installing the correct reference in the project, even if the project platform is set to 64-bit: https://github.com/pythonnet/pythonnet/issues/472.

Usually the x86 reference gets installed, and if your Python is 64-bit, you get the above exception.

To fix this:

  • Remove the existing assembly reference from the project.
  • Manually add reference to the correct assembly from the installed nuget package (e.g. your_solution_dir\packages\pythonnet_py35_dotnet.2.3.0\lib\net40\x64\Python.Runtime.dll)
like image 185
ika Avatar answered Sep 05 '25 16:09

ika


Changed the CPU architecture from AnyCPU to x64 and it fixed the issue.

like image 23
Chamupathi Gigara Hettige Avatar answered Sep 05 '25 15:09

Chamupathi Gigara Hettige