He utilizado el enfoque "estándar" de Embedding Python in Another Application. Pero es complicado/tedioso. Cada nueva función en Python es dolorosa de implementar.
Vi un ejemplo de Calling PyPy from C. Utiliza CFFI para simplificar la interfaz, pero requiere PyPy, no Python. Lea y comprenda este ejemplo primero, al menos en un nivel alto.
Modifiqué el ejemplo de C/PyPy para trabajar con Python. A continuación, se indica cómo llamar a Python desde C usando CFFI.
Mi ejemplo es más complicado porque implementé tres funciones en Python en lugar de una. Quería cubrir aspectos adicionales de pasar datos de ida y vuelta.
La parte complicada ahora está aislada para pasar la dirección de api
a Python. Eso solo tiene que implementarse una vez. Después de eso, es fácil agregar nuevas funciones en Python.
interface.h
// These are the three functions that I implemented in Python.
// Any additional function would be added here.
struct API {
double (*add_numbers)(double x, double y);
char* (*dump_buffer)(char *buffer, int buffer_size);
int (*release_object)(char *obj);
};
test_cffi.c
//
// Calling Python from C.
// Based on Calling PyPy from C:
// http://doc.pypy.org/en/latest/embedding.html#more-complete-example
//
#include <stdio.h>
#include <assert.h>
#include "Python.h"
#include "interface.h"
struct API api; /* global var */
int main(int argc, char *argv[])
{
int rc;
// Start Python interpreter and initialize "api" in interface.py using
// old style "Embedding Python in Another Application":
// https://docs.python.org/2/extending/embedding.html#embedding-python-in-another-application
PyObject *pName, *pModule, *py_results;
PyObject *fill_api;
#define PYVERIFY(exp) if ((exp) == 0) { fprintf(stderr, "%s[%d]: ", __FILE__, __LINE__); PyErr_Print(); exit(1); }
Py_SetProgramName(argv[0]); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString(
"import sys;"
"sys.path.insert(0, '.')");
PYVERIFY(pName = PyString_FromString("interface"))
PYVERIFY(pModule = PyImport_Import(pName))
Py_DECREF(pName);
PYVERIFY(fill_api = PyObject_GetAttrString(pModule, "fill_api"))
// "k" = [unsigned long],
// see https://docs.python.org/2/c-api/arg.html#c.Py_BuildValue
PYVERIFY(py_results = PyObject_CallFunction(fill_api, "k", &api))
assert(py_results == Py_None);
// Call Python function from C using cffi.
printf("sum: %f\n", api.add_numbers(12.3, 45.6));
// More complex example.
char buffer[20];
char * result = api.dump_buffer(buffer, sizeof buffer);
assert(result != 0);
printf("buffer: %s\n", result);
// Let Python perform garbage collection on result now.
rc = api.release_object(result);
assert(rc == 0);
// Close Python interpreter.
Py_Finalize();
return 0;
}
interface.py
import cffi
import sys
import traceback
ffi = cffi.FFI()
ffi.cdef(file('interface.h').read())
# Hold references to objects to prevent garbage collection.
noGCDict = {}
# Add two numbers.
# This function was copied from the PyPy example.
@ffi.callback("double (double, double)")
def add_numbers(x, y):
return x + y
# Convert input buffer to repr(buffer).
@ffi.callback("char *(char*, int)")
def dump_buffer(buffer, buffer_len):
try:
# First attempt to access data in buffer.
# Using the ffi/lib objects:
# http://cffi.readthedocs.org/en/latest/using.html#using-the-ffi-lib-objects
# One char at time, Looks inefficient.
#data = ''.join([buffer[i] for i in xrange(buffer_len)])
# Second attempt.
# FFI Interface:
# http://cffi.readthedocs.org/en/latest/using.html#ffi-interface
# Works but doc says "str() gives inconsistent results".
#data = str(ffi.buffer(buffer, buffer_len))
# Convert C buffer to Python str.
# Doc says [:] is recommended instead of str().
data = ffi.buffer(buffer, buffer_len)[:]
# The goal is to return repr(data)
# but it has to be converted to a C buffer.
result = ffi.new('char []', repr(data))
# Save reference to data so it's not freed until released by C program.
noGCDict[ffi.addressof(result)] = result
return result
except:
print >>sys.stderr, traceback.format_exc()
return ffi.NULL
# Release object so that Python can reclaim the memory.
@ffi.callback("int (char*)")
def release_object(ptr):
try:
del noGCDict[ptr]
return 0
except:
print >>sys.stderr, traceback.format_exc()
return 1
def fill_api(ptr):
global api
api = ffi.cast("struct API*", ptr)
api.add_numbers = add_numbers
api.dump_buffer = dump_buffer
api.release_object = release_object
de compilación:
gcc -o test_cffi test_cffi.c -I/home/jmudd/pgsql-native/Python-2.7.10.install/include/python2.7 -L/home/jmudd/pgsql-native/Python-2.7.10.install/lib -lpython2.7
Ejecutar:
$ test_cffi
sum: 57.900000
buffer: 'T\x9e\x04\x08\xa8\x93\xff\xbf]\x86\x04\x08\x00\x00\x00\x00\x00\x00\x00\x00'
$
¿Cuál es su razón para querer poner el programa en Python en un proceso separado, y no querer incorporar un intérprete de Python? Soy curioso. –
Bueno, si él puede abrirse camino con cadenas de tuberías a Python y luego de vuelta a C cuando está hecho, parece mucho más simple que incrustar un intérprete de Python. Simplemente llamar a una aplicación de Python por separado requerirá 5 minutos de integración si la interfaz es simple (simplemente pase cadenas y cadenas) y estoy seguro de que insertar un intérprete llevará un poco más de 5 minutos – hhafez
Aquí un ejemplo completo https: // desbordamiento de pila.com/a/46441794/5842403 donde puede ver Python incorporado en C, y luego C incrustado en Systemverilog usando DPI. – Joniale