---
# System prepended metadata

title: Python embedding with c
tags: [C, python, rewrite]

---

Python embedding with c
===
:::info
I think rewrite this would be better
:::
###### tags: `python` `C`

https://docs.python.org/2.7/extending/extending.html
https://www6.software.ibm.com/developerworks/education/l-pythonscript/l-pythonscript-ltr.pdf

# [Embedding Python in Another Application](https://docs.python.org/2.7/extending/embedding.html)

Embedding Python is similar to extending it, but not quite. The difference is that when you extend Python, the main program of the application is still the Python interpreter, while if you embed Python, the main program may have nothing to do with Python — instead, some parts of the application occasionally call the Python interpreter to run some Python code.

## Compiling and Linking under Unix-like systems

**Compile flags**

  ubuntu:
    python2.7-config —cflags: for compile c flags information
    python2.7-config —ldflags: for linking c flags information


## 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.

When embedding Python, the interface code does:

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.

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 running the comment:

    $ call multiply multiply 3 2

first you have to set the path

    $ PYTHONPATH=. ./call_function pyfunction multiply 2 3

equal to:

    import sys
    sys.path.insert(0, "./path/to/your/modules/")

so change it into code:
Put the following in the C/C++ code, just after `Py_Initialize();` 

    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append(\".\")");

or setenv() in #include <stdlib.h>

    setenv("PYTHONPATH",".",1);


