Extending and Embedding Python, Release 3.9.5 Chapter 3. Embedding the CPython runtime in a larger application 62 Upon return of the function,$_{pValue}$is either$_{NULL}$ or it contains a reference to the return value of the function. Be sure to release the reference after examining the value. (continued from previous page) fprintf(stderr, "Cannot find function " %s "
 ", argv[ 2]); } Py_XDECREF(pFunc); Py_DECREF(pModule); } else { PyErr_Print(); fprintf(stderr, "Failed to load " %s "
 ", argv[ 1]); return 1; } if (Py_FinalizeEx() <0) { return 120 ; } return 0; } This code loads a Python script using argv[1] , and calls the function named in argv[2] . Its integer arguments are the other values of the$_{argv}$array. If you compile and link this program (let’s call the finished executable$_{call}$ ), and use it to execute a Python script, such as: def multiply (a,b): print("Will compute ", a,"times", b) c =0 for i in range(0, a): c =c +b return c $ call multiply multiply 32 Will compute 3 times 2 Result of call: 6 Py_Initialize(); pName =PyUnicode_DecodeFSDefault(argv[ 1]); /* Error checking of pName left out */ pModule =PyImport_Import(pName); pFunc =PyObject_GetAttrString(pModule, argv[ 2]); /* pFunc is a new reference */ if (pFunc&&PyCallable_Check(pFunc)) { ... } Py_XDECREF(pFunc); then the result should be: Although the program is quite large for its functionality, most of the code is for data conversion between Python and C, and for error reporting. The interesting part with respect to embedding Python starts with After initializing the interpreter, the script is loaded using$_{PyImport_Import()}$ . This routine needs a Python string as its argument, which is constructed using the$_{PyUnicode_FromString()}$ data conversion routine. Once the script is loaded, the name we’re looking for is retrieved using$_{PyObject_GetAttrString()}$ . If the name exists, and the object returned is callable, you can safely assume that it is a function. The program then proceeds by constructing a tuple of arguments as normal. The call to the Python function is then made with: pValue=PyObject_CallObject(pFunc, pArgs);