I'm working on a c++ project that needs some functionalities included in a python library (scipy.stats). I created my python script that uses the libray and my idea is to pass the data from c++ to the python script, call the function and get the return value from python. But then when I do PyImport_Import(pName), it returns null because the module start with an import. If I use another script that doesn't start with an import it works fine. What am I doing wrong?
chi2.py:
from scipy.stats import chi2, chi2_contingency
def chi2Test(alpha):
# contingency table
table = [ [2556, 9327, 1028, 564],
[770, 2991, 322, 164],
[433, 1566, 182, 97]
]
stat, p, dof, expected = chi2_contingency(table)
# interpret p-value
if p <= alpha:
return False
else:
return True
(table is just a placeholder, in the future it will become a parameter)
main.cpp:
#include <stdio.h>
#include <conio.h>
#include <iostream>
#include <chrono>
#include <random>
#include <windows.h>
#include <string>
#include <iostream>
#include "pyhelper.hpp"
int main() {
CPyInstance hInstance;
CPyObject pName = PyUnicode_FromString("chi2");
CPyObject pModule = PyImport_Import(pName);
if (pModule)
{
CPyObject pFunc = PyObject_GetAttrString(pModule, "chi2Test");
if (pFunc && PyCallable_Check(pFunc))
{
CPyObject pArgs = PyTuple_New(0);
CPyObject pArg = PyFloat_FromDouble(0.5);
PyTuple_SetItem(pArgs, 0, pArg);
CPyObject pValue = PyObject_CallObject(pFunc, pArgs);
bool res = PyObject_IsTrue(pValue);
}
else
{
printf("ERROR: function getInteger()\n");
}
}
else
{
printf_s("ERROR: Module not imported\n");
}
return 0;
}
CPyInstance and CPyObject are 2 classes defined as specified here: https://www.codeproject.com/Articles/820116/Embedding-Python-program-in-a-C-Cplusplus-code
Thanks to anyone that can help or has suggestions to give. (It is the first time I'm working on c++ with python embedded)