我正在使用Visual Studio用C#创建一个应用程序,它将运行一些Python脚本并获取它们的返回值。为此,我想使用Python.Net(或适用于.Net的Python)。我通过anaconda安装了Python.Net。
但是,如果我运行该程序,则会收到未找到python36.dll的错误消息:
System.DllNotFoundException: Unable to load DLL 'python36':
The specified module could not be found
如果我想加载anaconde的python36.dll作为对我的项目的引用,我会得到:
Reference "C:\Programm Files (x86\Micrtosoft\Visual Studio\Shared\Anaconde3_64\python36.dll" can't be
added, Please make sure that the file is accessible and that it is
a valid assembly or COM component.
我尝试使用以下方式注册dll:
regsvr32
也不起作用。
答案 0 :(得分:0)
根据this post,
该文件是本机DLL,这意味着您无法通过“添加引用”将其添加到.NET项目中...可以通过 DllImport 使用它 看到, http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.aspx
示例-DllImportAttribute属性,以导入 Win32 MessageBox 函数。
using System;
using System.Runtime.InteropServices;
class Example
{
// Use DllImport to import the Win32 MessageBox function.
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
static void Main()
{
// Call the MessageBox function using platform invoke.
MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
}
}
答案 1 :(得分:0)
最后,我找到了解决方案/解决方法。对于Python.Net,此错误似乎是一个更常见的问题,他们在github站点(https://github.com/pythonnet/pythonnet/issues/708)上已解决了一些问题
var pythonPath = @"C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python3_64";
Environment.SetEnvironmentVariable("PATH", $@"{pythonPath};" + Environment.GetEnvironmentVariable("PATH"));
Environment.SetEnvironmentVariable("PYTHONHOME", pythonPath);
Environment.SetEnvironmentVariable("PYTHONPATH ", $@"{pythonPath}\Lib");
PythonEngine.PythonHome = @"C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64";
using (Py.GIL())
{
dynamic np = Py.Import("numpy");
Console.WriteLine(np.cos(np.pi * 2));
}