A High-Level Embedding API: ppembed

As you can probably tell from Example 23-14, embedded-mode integration code can very quickly become as complicated as extending code for nontrivial use. Today, no automation solution solves the embedding problem as well as SWIG addresses extending. Because embedding does not impose the kind of structure that extension modules and types provide, it’s much more of an open-ended problem; what automates one embedding strategy might be completely useless in another.

With a little upfront work, though, you can still automate common embedding tasks by wrapping up calls in higher-level APIs that make assumptions about common use cases. These APIs could handle things such as error detection, reference counts, data conversions, and so on. One such API, ppembed, is available in this book’s examples distribution. It merely combines existing tools in Python’s standard C API to provide a set of easier-to-use calls for running Python programs from C.

Running Objects with ppembed

For instance, Example 23-15 demonstrates how to recode objects-err-low.c in Example 23-14, by linking ppembed’s library files with your program.

Example 23-15. PP3E\Integrate\Embed\ApiClients\object-api.c

#include <stdio.h> #include "ppembed.h" main ( ) { /* with ppembed high-level api */ int failflag; PyObject *pinst; char *arg1="sir", *arg2="robin", *cstr; failflag = PP_Run_Function("module", "klass", "O", &pinst, "( )") || PP_Run_Method(pinst, "method", "s", &cstr, "(ss)", arg1, arg2); ...

Get Programming Python, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.