C# calls the pyd file generated by Python

1. Create a C# console program.

2.vs2017 install pythonnet_netstandard_py37_win

First open the nuget package manager:

Enter NuGet\Install-Package pythonnet_netstandard_py37_win -Version 2.5.2

3. Related codes

//Set up the conda environment                

var pathToVirtualEnv = @"C:\Users\SXM\anaconda3\envs\suff";
                Environment.SetEnvironmentVariable("PATH", pathToVirtualEnv, EnvironmentVariableTarget.Process);
                Environment.SetEnvironmentVariable("PYTHONHOME", pathToVirtualEnv, EnvironmentVariableTarget.Process);
                Environment.SetEnvironmentVariable("PYTHONPATH", $"{pathToVirtualEnv}\\Lib\\site-packages;{pathToVirtualEnv}\\Lib",
                    EnvironmentVariableTarget.Process);

using (Py.GIL()) // Use this to wrap the code you call the python method
            {                 // First introduce the python module, which is the pyd file we generated above, such as my_module.cp36-win_amd64.pyd                 dynamic my_module = Py. Import("train");

                // First import the python module, which is the pyd file we generated above, such as my_module.cp36-win_amd64.pyd
                dynamic my_module = Py.Import("train");
                // Call your python functions.
             // Call your python functions.

                my_module.func(arg1, arg2);
            }

Possible errors:

1. Unable to load DLL 'python37': The specified module could not be found. (Exception from HRESULT: 0x8007007E).

Solution: Find python37.dll in the python environment and put it in the C# project x64\Debug file.

 

 

Guess you like

Origin blog.csdn.net/sxmsxmsmxm/article/details/127280142