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?