0

I am trying to use sympy with my c++ program and am using the following embedding code to do that.

int sym_ex(const char * input_expression, const char * output_expression){

    PyObject *pName, *pModule, *pDict, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    const char * file = "sympy";
    const char * function = "simplify";


    Py_Initialize();
    //PyRun_SimpleString("from sympy import *\n");
    pName = PyString_FromString(file);
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, function);
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) {

            pArgs = PyTuple_New(1);
            pValue = PyString_FromString(input_expression);
            printf("the string passed %s\n", input_expression);
            if (!pValue) {
                Py_DECREF(pArgs);
                Py_DECREF(pModule);
                fprintf(stderr, "Cannot convert argument\n");
                return 1;
            }
            /* pValue reference stolen here: */
            PyTuple_SetItem(pArgs, 0, pValue);

            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                printf("Result of call: %s\n", PyString_AsString(pValue));
                Py_DECREF(pValue);
            }
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr, "Call failed\n");
                return 1;
            }
        }
        else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", function);
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", file);
        return 1;
    }
    Py_Finalize();
    return 0;

}

But, when I write a small program using this function and run it,

#include <stdio>
#include <iostream>

int main(){

char * input_expression = "2 + 2";
char * output_expression = new char[250];

sym_ex(input_expression, output_expression);

return 0;
}

It gives out the following type error. I am running on windows in Visual C++, Python 2.7.8

 Exception TypeError: 'expected string or Unicode object, Integer found' in <module 'threading' from 'C:\Python278\Lib\threading.pyc'> ignored

Can somebody help me? Thanks

Charith
  • 1
  • 1

1 Answers1

0

The problem here is the call to String_AsString(pValue)

printf("Result of call: %s\n", PyString_AsString(pValue));

The result of sympy.simplify("2+2") is 4, which is an integer and not a string. The result is that Python raises an TypeError exception.

If you want a string as the result you should probably first call PyObject_Str(pValue) and then convert it into a C string.

sterin
  • 1,898
  • 15
  • 13