1

I have a C++ script that I run in Visual studio 2022 on windows 10 and where I include the python module. In the code I import numpy in a for-loop. The code executes fine the first round, but in the second round and exception is thrown as soon as the code tries to execute the import statement. I have googled for the error and searched for similar issues on stackOverflow but not found any solution. I have also isolated the error and made a minimal example. Here is the code from the example:

#include <C:\Program Files\Python39\include\Python.h>
#include <iostream>

using namespace std;

int main() {

    for (int i = 0; i < 5; i++) {
        cout << i << endl;

        Py_Initialize();
        PyRun_SimpleString("import numpy as np"); 
        PyRun_SimpleString("arr = np.array([1,2,3])");
        PyRun_SimpleString("print(arr)");
        Py_Finalize();

    }
}

This is the output from the console when running the code:

0
[1 2 3]
1
Traceback (most recent call last):
  File "<string>", line 1, in <module>

Here is the error message in visual studio:

Exception thrown at 0x00007FFCB9461319 (_multiarray_umath.cp39-win_amd64.pyd) in App4.exe: 0xC0000005: Access violation writing location 0x0000000000000008.

What could be going on here and how can I solve it?

Johan hvn
  • 318
  • 1
  • 2
  • 11
  • It might not solve your problem but it's possible that `Py_Finalise()` doesn't wait for the interpreter to close. In this case, the next `Py_Initialize()` call would try to access a file that is still open and could throw this kind of error. In any case, opening and closing the interpreter is not inexpensive, and really should only be performed at the start and end of the program respectively. – Cmd858 Dec 20 '22 at 14:12
  • 2
    There are a lot of caveats on https://docs.python.org/3/c-api/init.html#c.Py_FinalizeEx including "Some extensions may not work properly if their initialization routine is called more than once" See also https://stackoverflow.com/questions/7676314/py-initialize-py-finalize-not-working-twice-with-numpy – Kenny Ostrom Dec 20 '22 at 15:15

0 Answers0