2

I have only been able to find tutorials and links for python 2 not any for 3. A lot of functions have changed since 2 and the tutorials no longer work.

I was able to take this from a another Stackoverflow question and it seems to be the closest to working.

char *my_result = 0;
PyObject *module = 0;
PyObject *result = 0;
PyObject *module_dict = 0;
PyObject *func = 0;
PyObject *pArgs = 0;

module = PyImport_ImportModule("testPython");
if (module == 0)
{
    PyErr_Print();
    printf("Couldn't find python module");
}
module_dict = PyModule_GetDict(module); 
func = PyDict_GetItemString(module_dict, "helloWorld"); 

//result = PyObject_CallObject(func, NULL);
result = PyEval_CallObject(func, NULL);
my_result = PyBytes_AsString(result);
my_result = strdup(my_result);

But the my_result outputs 0000. And when using a breakpoint it says it cannot read the memory.

3
  • what isn't working? Are there error messages? Compile-time? runtime? Commented Mar 19, 2014 at 6:10
  • @mgilson I updated my question at the bottom. "But the my_result outputs 0000. And when using a breakpoint it says it cannot read the memory." Commented Mar 19, 2014 at 6:19
  • error handling 101: 1) always check the return value 2) if something unrecoverable happens, don't continue. Commented Mar 19, 2014 at 7:13

1 Answer 1

1

Try this:

static float CallPythonFunc()
{
    PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *pArgs;
    float ret;

    Py_Initialize();

    pName = PyBytes_FromString("py");

    pModule = PyImport_ImportModule("py");

    pDict = PyModule_GetDict(pModule);

    pFunc = PyDict_GetItemString(pDict, "add");


    if (PyCallable_Check(pFunc))
    {
        pArgs = PyTuple_New(2 /*number of arguments*/);

        // Argument 1
        pValue = PyFloat_FromDouble((double)5);
        PyTuple_SetItem(pArgs, 0, pValue);

        // Argument 2
        pValue = PyFloat_FromDouble((double)6);
        PyTuple_SetItem(pArgs, 1, pValue);

        pValue = PyObject_CallObject(pFunc, pArgs);

        ret = (float)PyFloat_AsDouble(pValue);

    }
    Py_Finalize();

    return ret;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.