(continued from previous page) Extending and Embedding Python, Release 3.9.5 Chapter 3. Embedding the CPython runtime in a larger application 60 This chapter will not discuss how to convert data from Python to C and vice versa. Also, proper use of references and dealing with errors is assumed to be understood. Since these aspects do not differ from extending the interpreter, you can refer to earlier chapters for the required information. As you can see, the data conversion steps are simply swapped to accommodate the different direction of the cross- language transfer. The only difference is the routine that you call between both data conversions. When extending, you call a C routine, when embedding, you call a Python routine. When embedding Python, the interface code does: It should be noted that extending Python and embedding Python is quite the same activity, despite the different intent. Most topics discussed in the previous chapters are still valid. To show this, consider what the extension code from Python to C really does: The high level interface gives you the ability to execute arbitrary pieces of Python code from your application, but exchanging data values is quite cumbersome to say the least. If you want that, you should use lower level calls. At the cost of having to write more C code, you can achieve almost anything. The$_{Py_SetProgramName()}$ function should be called before$_{Py_Initialize()}$ to inform the interpreter about paths to Python run-time libraries. Next, the Python interpreter is initialized with Py_Initialize() , followed by the execution of a hard-coded Python script that prints the date and time. Afterwards, the Py_FinalizeEx() call shuts the interpreter down, followed by the end of the program. In a real program, you may want to get the Python script from another source, perhaps a text-editor routine, a file, or a database. Getting the Python code from a file can better be done by using the$_{PyRun_SimpleFile()}$ function, which saves you the trouble of allocating memory space and loading the file contents. main( int argc, char *argv[]) { wchar_t *program =Py_DecodeLocale(argv[ 0],NULL ); if (program==NULL ) { fprintf(stderr, "Fatal error: cannot decode argv[0] "); exit(1); } Py_SetProgramName(program); /* optional but recommended */ Py_Initialize(); PyRun_SimpleString( "from time import time,ctime " "print('Today is', ctime(time())) "); if (Py_FinalizeEx() <0) { exit(120 ); } PyMem_RawFree(program); return 0; } 3.1.2 Beyond Very High Level Embedding: An overview 1. Convert data values from Python to C, 2. Perform a function call to a C routine using the converted values, and 3. Convert the data values from the call from C to Python. 1. Convert data values from C to Python, 2. Perform a function call to a Python interface routine using the converted values, and 3. Convert the data values from the call from Python to C.