The python module i am importing in C++ with the Python/C API can't import torch

  • OS: Windows 10
  • C++ environment was created in Visual Studio Community 2017 with CMake.

I have a C++ file importing a Python module and calling a function from it, everything seems to properly work until i do an “import torch” in the Python file.

** C++ CallPython function: **

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());
DBG(“initialize the Python interpreter”);
TCHAR cwd[2048];
GetCurrentDirectory(sizeof(cwd), cwd);
DBG(“Load the Python module”);
PyObject* my_module = PyImport_ImportModule(modname);
DBG(“Module found”);
DBG(" find function from Python module");
DBG(“Getting address of the funct in Python module”);
PyObject* my_function = PyObject_GetAttrString(my_module, funcname);
DBG(“Function found”);
DBG(“call function from Python module”);
PyObject* my_result = PyObject_CallObject(my_function, NULL);
DBG(“Your function has been called”);
delete funcname;
delete modname;}

**C++ main: **

CallPython(“PythonFile2”, “helloworld”);

**Python file named **

import re
import string
import yaml
#import torch
def helloworld():
fh = open(‘myfile.txt’, ‘w’)

de-commenting the “import torch” line results in a “access violation while reading” exception generated by the “PyObject_GetAttrString” function. I think the problem is that i am not working in the properly python environment and the one that i am in doesn’t have torch installed, but i have no idea how to set the python environment from the C++ application.

Thanks for your attention!

Were you ever able to solve this? I’m running into the same issue.