Embed Sympy in Qt C++ application

57 views
Skip to first unread message

J. Javan

unread,
Jan 24, 2018, 2:23:35 PM1/24/18
to sympy
Hey guys,
I have a C++ application and I want to embed sympy in it.
Application is statically linked against python.
However, I'm facing a problem when importing sympy module which simply doesn't get imported.
Are there any examples on this?

Below is my code:


const char * python_home = "\"C:\\Program Files\\Python3.6.4\"";

int
main(int argc, char *argv[])
{
    PyObject *pName = nullptr;
    PyObject *pModule = nullptr;
    PyObject *pDict = nullptr;
    PyObject *pFunc = nullptr;
    PyObject *pValue = nullptr;
    PyObject *pMainModule = nullptr;

   
Py_SetProgramName((wchar_t *) APP_NAME);
    Py_Initialize();
Py_SetPythonHome((wchar_t *) python_home);
    PyRun_SimpleString("import sys");


PyRun_SimpleString("sys.path.append(\"C:\\Program Files\\Python3.6.4\")"); if(PyErr_Occurred()) {
        // error handling
}
    pName
= PyBytes_FromString("sympy");
    if(nullptr == pName)
    {
        // error handling
    }

// Below function call always fails
    pModule
= PyImport_Import(pName);
    if(nullptr == pModule)
    {
PyObject *ptype, *ptraceback; PyObject *pystr = nullptr; char *str;
PyObject
*pErrMsg = nullptr; PyErr_Fetch(&ptype, &pErrMsg, &ptraceback);
       
str = PyBytes_AsString(pystr);    // str is always null
}


return 0;
}


I have Installed python and ran below command to install sympy:
pip3 install sympy

Dev Environment:
Qt_v5.9
Windows 7
Python_v3.6.4

Kasper Peeters

unread,
Jan 25, 2018, 6:56:24 AM1/25/18
to sympy
I know you didn't ask for this, but I can strongly recommend using pybind11 (https://github.com/pybind/pybind11) if you want nice C++ bindings for Python. It shields you from a lot of low-level details.

J. Javan

unread,
Jan 30, 2018, 7:05:03 AM1/30/18
to sympy
Thank you for your reply. I'll have a look.
I managed to get around the problem by simply changing below line of code


pName = PyBytes_FromString("sympy");

to

pModuleName = PyUnicode_FromString("sympy.combinatorics");
Reply all
Reply to author
Forward
0 new messages