Nick
Nick

Reputation: 147

Can not add python.dll as reference to Visual Studio project

I am creating an application in C# with Visual Studio, which shall run some Python-Scripts and get their return values. For that I want to use Python.Net (or Python for .Net). I installed Python.Net via anaconda.

But if I run the program I get the error that the python36.dll was not found:

    System.DllNotFoundException: Unable to load DLL 'python36': 
    The specified module could not be found

If I want to load the python36.dll of anaconde as a reference to my project I get:

    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.

I tried to register the dll with:

    regsvr32 

did not work either.

Upvotes: 1

Views: 2868

Answers (2)

Nick
Nick

Reputation: 147

Finally I found a solution/workaround. This error seems to be a more common problem to Python.Net and they have some solved issues on their github site (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));
        }

Upvotes: 2

HasithaJay
HasithaJay

Reputation: 375

According to this post,

the file is a native DLL which means you can't add it to a .NET project via Add Reference... you can use it via DllImport see, http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.aspx

Example -DllImportAttribute attribute to import the Win32 MessageBox function.

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

Upvotes: 0

Related Questions