Cannot import torch via c++ interpreter

username: jchmack
cooked: <p>I currently have this .py file working in both the c++ interpreter and python itself</p>
<p>import string<br>
<span class="hashtag-raw">#import</span> torch<br>
def PyMain():<br>
print(“Hello from Python!”)</p>
<p>But if i uncomment the “import torch” i get this error:</p>
<blockquote>
<p>Traceback (most recent call last):<br>
File “C:\Users\J\Desktop\Game17\Game17\x64\Debug\JPytorch.py”, line 24, in <br>
import torch<br>
File “C:\Users\J\AppData\Local\Programs\Python\Python310\lib\site-packages\torch_<em>init</em>_.py”, line 122, in <br>
raise err<br>
OSError: [WinError 127] The specified procedure could not be found. Error loading “C:\Users\J\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\lib\c10_cuda.dll” or one of its dependencies.</p>
</blockquote>
<p>the code calling python is:</p>
<pre><code class="lang-auto">void CallPython(string PythonModuleName, string PythonFunctionName)
{
	char* funcname = new char[PythonFunctionName.length() + 1];
	strcpy_s(funcname, PythonFunctionName.length() + 1, PythonFunctionName.c_str());

	char* modname = new char[PythonModuleName.length() + 1];
	strcpy_s(modname, PythonModuleName.length() + 1, PythonModuleName.c_str());

	std::wstring pythonHome = L"C:/Users/J/AppData/Local/Programs/Python/Python310";
	//std::wstring pythonHome = L"C:/Users/J/AppData/Local/Microsoft/WindowsApps";
	Py_SetPythonHome(pythonHome.c_str());

	std::wstring pythonExecutablePath = L"C:/Users/J/AppData/Local/Programs/Python/Python310/python.exe";
	Py_SetProgramName(const_cast&lt;wchar_t*&gt;(pythonExecutablePath.c_str()));

	Py_Initialize();

	TCHAR cwd[2048];
	GetCurrentDirectory(sizeof(cwd), cwd);

	//separated with the platform’s search path delimiter (: on Unix, ; on Windows).
	//No spaces before/after ';'
	wstring Finalpath;
	//Finalpath += L"D:\\Gamedev Shared\\Source\\Python;";
	Finalpath += L"C:\\Users\\J\\Desktop\\Game17\\Game17\\x64\\Debug;"; 
	Finalpath += L"C:\\Users\\J\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip;"; 
	Finalpath += L"C:\\Users\\J\\AppData\\Local\\Programs\\Python\\Python310\\DLLs;"; 
	Finalpath += L"C:\\Users\\J\\AppData\\Local\\Programs\\Python\\Python310\\Lib;";
	Finalpath += L"C:\\Users\\J\\AppData\\Local\\Programs\\Python\\Python310;";
	Finalpath += L"C:\\Users\\J\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages;";
	//Finalpath += L"C:\\\\Users\\\\J\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python310\\\\lib\\\\site-packages\\\\;";

	PySys_SetPath(Finalpath.c_str()); 
     
	PyObject* my_module = PyImport_ImportModule(modname);

	// Print a standard traceback to sys.stderr and clear the error indicator
	// https://docs.python.org/3/c-api/exceptions.html?highlight=pyerr_print#c.PyErr_Print
	PyErr_Print();

	// Get the address of the particular Python function in the imported module
	// https://docs.python.org/3/c-api/object.html?highlight=pyobject_getattrstring#c.PyObject_GetAttrString
	//printf("Getting address of %s in Python module\\n", funcname);
	PyObject* my_function = PyObject_GetAttrString(my_module, funcname);
	PyErr_Print();

	// Call a callable Python object callable, with arguments given by the tuple args. 
	// If no arguments are needed, then args can be NULL.
	// https://docs.python.org/3/c-api/call.html?highlight=pyobject_callobject#c.PyObject_CallObject
	PyObject* my_result = PyObject_CallObject(my_function, NULL);
	PyErr_Print();

	//printf("Your function has been called\\n");
	//system("pause");

	// Undo all initializations made by Py_Initialize() and subsequent use of Python/C API functions, 
	// and destroy all sub-interpreters (see Py_NewInterpreter() below) that were created and not yet 
	// destroyed since the last call to Py_Initialize(). Ideally, this frees all memory allocated by the Python interpreter.
	// https://docs.python.org/3/c-api/init.html?highlight=py_finalize#c.Py_FinalizeEx
	Py_Finalize();

	delete[] funcname;
	delete[] modname;
}
</code></pre>
<p>I honestly don’t get why the plain .py file would work but not when called via the interpreter.</p>
<p>Edit:<br>
I found this guy having the exact same problem:<br>
<a href="https://stackoverflow.com/questions/76054754/the-python-module-i-am-importing-in-c-with-the-python-c-api-can-t-import-torch" class="inline-onebox" rel="noopener nofollow ugc">The python module i am importing in C++ with the Python/C API can’t import torch - Stack Overflow</a>.</p>
<p>print(“Python Version:”, sys.version)<br>
print(“Python Path:”, sys.path)</p>
<p>I have the exact same version and path in both the .py version and the c++ interpreter version.<br>
If I navigate to : “C:\Users\J\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\lib\c10_cuda.dll”  I can see it in explorer but for some reason python can’t.</p>

username: jchmack
cooked: <p>Figured it out mostly…<br>
If you have libtorch included in you c++ project, Libtorch loads a conflicting .dll file.</p>
<p>I would figure that libtorch loading a .dll in c++ would just allow “import torch” via interpreter to use that same dll, but as long as I got it working I guess I don’t need both.</p>