gpt4 book ai didi

python.net - 使用 NuGet 为 .net 设置 pythonnet

转载 作者:行者123 更新时间:2023-12-04 14:18:48 24 4
gpt4 key购买 nike

我正在尝试开发一个在 .net 中嵌入 python 的简单计算器程序,我想从 NuGet 中引用 pythonnet 以将其包含在我的项目中

我使用 NuGet 安装了 pythonnet v2.3.0,我的系统中还安装了 python 3

如果有人能一步一步地指导我嵌入 python 网络,那就太好了

form1.cs 代码:

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");
}
}
}
}

当我在代码中使用 using(Py.GIL()) 行时,编译器会显示

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.'

最佳答案

此问题可能是由 Python.Runtime.dll 与您的 Python 之间的架构(32 位/64 位)不匹配引起的。

目前在 nuget.org 上发布的 pythonnet 2.3.0 NuGet 包包括两个版本的 Python.Runtime.dll 程序集:32 位 (x86) 和 64 位 (x64)。此包存在一个已知问题,无法在项目中安装正确的引用,即使项目平台设置为 64 位也是如此: https://github.com/pythonnet/pythonnet/issues/472 .

通常会安装 x86 引用,如果您的 Python 是 64 位,则会出现上述异常。

解决这个问题:

  • 从项目中删除现有程序集引用。
  • 从已安装的 nuget 包中手动添加对正确程序集的引用(例如 your_solution_dir\packages\pythonnet_py35_dotnet.2.3.0\lib\net40\x64\Python.Runtime.dll)

关于python.net - 使用 NuGet 为 .net 设置 pythonnet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57274830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com