Question

Below is the c++ code, it will call my python script 'rule.py' in the same directory.

#include <Python.h>
#include <iostream>
using namespace std;

int dou(int a)
{
    PyObject *pModule, *pDict, *pFunc, *pArgs, *pRetVal;
    if( !Py_IsInitialized() ){
        cout<<"Can't initialize"<<endl;
        return -1;
    }
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('.')");
    pModule = PyImport_ImportModule("rule");
    if( !pModule ){
        cout<<"can' import the module "<<endl;
        return -1;
    }
    pDict = PyModule_GetDict(pModule);
    if( !pDict ){
        cout<<"can't get the dict"<<endl;
        return -1;
    }
    pFunc = PyDict_GetItemString(pDict, "fun");
    if( !pFunc || !PyCallable_Check(pFunc) ){
        cout<<"can't get the function"<<endl;
        return -1;
    }

    pArgs = PyTuple_New(1);
    PyTuple_SetItem(pArgs,0,Py_BuildValue("i",a));
    pRetVal = PyObject_CallObject(pFunc,pArgs);

    int result = PyInt_AsLong(pRetVal);

    Py_DECREF(pModule);
    Py_DECREF(pDict);
    Py_DECREF(pFunc);
    Py_DECREF(pArgs);
    Py_DECREF(pRetVal);

    return result;
}
int main(void)
{
    Py_Initialize();
    cout<<dou(2)<<endl;
    cout<<dou(3)<<endl;
    Py_Finalize();
    return 0;
}

And this is the simple python code.

def fun(a):
    return 2*a
if __name__ == "__main__":
    print fun(2)

The output is :

4
can't get the function.
-1

It works at first time but can't get the function when call it at the second time. Maybe something I have missed?

Was it helpful?

Solution

PyModule_GetDict() returns a borrowed reference. It means you must not decrease its reference count, or that the module dict will be destructed.

There are many errors in your code piece. I think you may try boost::python. And read the Python manual carefully, especially in reference count management.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top