I have made a Python file that contains a function which returns the Taylor series of the generating function of a recurrence relation. I want to run this function from a C++ program. Now the problem I am facing is that when I run the Python file from the C++ program without importing any external libraries(namely, sympy, as that is what I have used in my Python file), the file runs fine and will output something like Hello World if I have written only simple commands like
print('Hello World')
in the Python file.
But when I import sympy and then run the file from the C++ program I get the following error -
Unhandled exception at 0x79BC85C2 (python37.dll) in merger.exe: 0xC0000005: Access violation reading location 0x00000004. occurred
The following is the code that I have written -
#include "Python.h"
#include<iostream>
#include<Windows.h>
using namespace std;
int main()
{
    Py_Initialize();
    PySys_SetPath(L"C:/Users/acer/PycharmProjects/justpractice");
    PyObject* pfile = PyImport_ImportModule("derivativecalc");
    PyObject* pclass = PyObject_GetAttrString(pfile, "CreatorClass"); < --  Line where the error occurs
    Py_Finalize();
    return 0;
}
The following is the code in my Python file. I am not using any functions that I defined until now.
import sympy as sy
from sympy.functions import sin, cos
x = sy.Symbol('x')
f = sin(x)
# Factorial function
def factorial(n):
    if n <= 0:
        return 1
    else:
        return n * factorial(n - 1)
# Taylor approximation at x0 of the function 'function'
def taylor(function, x0, n):
    i = 0
    p = 0
    while i <= n:
        p = p + (function.diff(x, i).subs(x, x0)) / (factorial(i)) * (x - x0) ** i
        i += 1
    return p
class CreatorClass:
    def creator(self, a1, a0, p, q):
        y = sy.Symbol('y')
        func1 = ((a0 + (a1 - p * a0)) * y) / (1 - p * y - q * (y ** 2))
        return taylor(func1, 0, 4)
print('Hello World')
I have no idea why the inclusion of some external libraries in my Python Program affects the output in the CPP Program. I have tried including the site-packages folder in my Python Libraries to the Debug folder of my project in Visual Studio but to no avail.
I learned to embed Python into C++ only today so you can think of me as a super beginner. Any help would be appreciated.
User contributions licensed under CC BY-SA 3.0