pythonc#python.net

Embedding Python libraries in C# project


I need to use a specific Python library (SciPy) in a C# application. Application will be deployed to machines that do not have Python installed, and it should not be a prerequisite. I am trying to use Pythonnet to integrate Python into my C# application. I downloaded and installed Pythonnet NuGet package via Visual Studio. I then copied Python311.dll to my solution folder (so it would be shipped with my application when installed on other machines), and I am now trying to test it with the code sample from Pythonnet docs:

    private void TestPython()
    {
        Runtime.PythonDLL = @"D:\Projects\MyProject\dlls\python311.dll";
        PythonEngine.Initialize();
        using (Py.GIL())
        {
            dynamic np = Py.Import("numpy");
            Console.WriteLine(np.cos(np.pi * 2));

            dynamic sin = np.sin;
            Console.WriteLine(sin(5));

            double c = (double)(np.cos(5) + sin(5));
            Console.WriteLine(c);

            dynamic a = np.array(new List<float> { 1, 2, 3 });
            Console.WriteLine(a.dtype);

            dynamic b = np.array(new List<float> { 6, 5, 4 }, dtype: np.int32);
            Console.WriteLine(b.dtype);

            Console.WriteLine(a * b);
            Console.ReadKey();
        }
    }

The python311.dll is recognized and accepted, but I get an error 'No module named 'numpy'' on line dynamic np = Py.Import("numpy");. This is, of course, because I don't have numpy library installed.

Problem is, if I install it via pip, the library DLLs will not be embedded into my application (they will be in C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib). I can probably copy them over to solution folder like I did with python311.dll, but I don't know how to tell Py to use them, rather than search for them in regular Python installation directories.

Can anyone advise?


Solution

  • Just copy the numpy library folder from your python installation folder ( let's say C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib) to your executable folder.

    Additionally, you need to tell python where is your library located. If you have several libraries, you can have a modules sub-folder on your executable folder. Then, the way we tell python to take that folder to search for modules is:

    using (Py.GIL())
    {
        dynamic sys = Py.Import("sys");
        sys.path.insert(0, ".\\modules");
        //...
    

    Put that before importing numpy. Hope it works!