0
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”);
    Py_Initialize();
    TCHAR cwd[2048];
    GetCurrentDirectory(sizeof(cwd), cwd);

    DBG(“Load the Python module”);
    PyObject* my_module = PyImport_ImportModule(modname);
    PyErr_Print();

    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);
    PyErr_Print();

    DBG(“Function found”);
    DBG(“call function from Python module”);
    PyObject* my_result = PyObject_CallObject(my_function, NULL);
    PyErr_Print();

    DBG(“Your function has been called”);
    Py_Finalize();

    delete[] funcname;
    delete[] modname;
}

**C++ main: **

CallPython(“PythonFile2”, “helloworld”);

**Python file named PythonFile2.py: **

import re
import string
import yaml
#import torch

def helloworld():
    fh = open(‘myfile.txt’, ‘w’)
    fh.write(‘testing’)
    fh.close()

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!

Edoar
  • 1
  • 1

0 Answers0