samedi 4 août 2018

Pass a variable number of parameters to an API

Today I was reading about embedded python in C++ at

https://docs.python.org/3/extending/embedding.html

So, I can call a python code in C++.

But the way python is called in the API example does not look cool to me.

I was thinking about calling a python function from C++ in any arbitrary way like:

py_call(script_path,module_name,str1,int2,long3,float4,str5,double6);

or

py_call(script_path,module_name,x,y,z,title);

But I need to use a parameter pack. This is the first time I see parameter pack. I have stuck right here and I do not know how to replace argc and argv parameters in the following code:

template<typename T, typename... Targs>
void py_call(
        const string &script,
        const string &module,
        T value, Targs... Fargs
    )
{
    PyObject *pName, *pModule, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    pName = PyUnicode_DecodeFSDefault(script.c_str());
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);
    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, module.c_str());
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_New(argc - 3);
            for (i = 0; i < argc - 3; ++i) {
                pValue = PyLong_FromLong(atoi(argv[i + 3]));
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument\n");
                    return 1;
                }
                /* pValue reference stolen here: */
                PyTuple_SetItem(pArgs, i, pValue);
            }
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                printf("Result of call: %ld\n", PyLong_AsLong(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", module.c_str());
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else
    {
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n",script.c_str());
        return 1;
    }
}

Aucun commentaire:

Enregistrer un commentaire