Sign in to follow this  

Python 3.3.2 Embedding

This topic is 1699 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am following this turorial and am not getting anywhere, with the code that was provided. I am running Python 3.3.2.

 

It returns null on

 

PyObject* pluginModule = PyImport_Import(name);

 

 

static const char* PLUGIN_NAME = "shout_filter";


String<> CallPlugIn(const String<>& ln)
{
    PyObject* name = PyBytes_FromString(PLUGIN_NAME);
    PyObject* pluginModule = PyImport_Import(name);
    Py_DECREF(name);
    if (!pluginModule)
    {
        PyErr_Print();
        return "Error importing module";
    }
    PyObject* filterFunc = PyObject_GetAttrString(pluginModule, "filterFunc");
    Py_DECREF(pluginModule);
    if (!filterFunc)
    {
        PyErr_Print();
        return "Error retrieving 'filterFunc'";
    }
    PyObject* args = Py_BuildValue("(s)", ln);
    if (!args)
    {
        PyErr_Print();
        Py_DECREF(filterFunc);
        return "Error building args tuple";
    }
    PyObject* resultObj = PyObject_CallObject(filterFunc, args);
    Py_DECREF(filterFunc);
    Py_DECREF(args);
    if (!resultObj)
    {
        PyErr_Print();
        return "Error invoking 'filterFunc'";
    }
    const char* resultStr = PyBytes_AsString(resultObj);
    if (!resultStr)
    {
        PyErr_Print();
        Py_DECREF(resultObj);
        return "Error converting result to C string";
    }
    String<> result = resultStr;
    Py_DECREF(resultObj);
    return result;
}

int RunThatPythonScript()
{
    Py_Initialize();
    PyObject* sysPath = PySys_GetObject((char*)"path");
    PyObject* curDir = PyBytes_FromString(".");
    PyList_Append(sysPath, curDir);
    Py_DECREF(curDir);
    String<> input = "Do Something With This Text";
    CallPlugIn(input);
    Py_Finalize();
    return 0;
}
 

 

I was getting the same issue with the official version demo:

 

http://docs.python.org/3/extending/embedding.html#embedding-python-in-c

 

Any suggestions?

Share this post


Link to post
Share on other sites

I made a modification to the start of the CallPlugIn function

 

 

    //PyObject* pluginModule = PyImport_Import(name);
    PyObject* pluginModule = PyImport_ImportModule(PLUGIN_NAME);
 

 

It got me further into the function, but the result string is null.

    const char* resultStr = PyBytes_AsString(resultObj);


 

 

 

Edit:

I tried this code and it got the right result.

    char *cstrret;
    PyArg_Parse(resultObj, "s", &cstrret);
 

 

I used this tutorial:

 

https://www6.software.ibm.com/developerworks/education/l-pythonscript/l-pythonscript-ltr.pdf

 

Its the only one I've found that works.



 

Edited by Davaris1

Share this post


Link to post
Share on other sites
Sign in to follow this