Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bluebanboom
Last active September 12, 2021 04:51
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save bluebanboom/5244436 to your computer and use it in GitHub Desktop.
Save bluebanboom/5244436 to your computer and use it in GitHub Desktop.
Example of embedding python in c.
#include <Python.h>
#include <stdio.h>
/*
* gcc embpython.c -I/usr/include/python2.7 -lpython
**/
void loadModule()
{
/* run objects with low-level calls */
char *arg1="sir", *arg2="robin", *cstr;
printf("Load Module err!\n");
PyObject *pmod, *pclass, *pargs, *pinst, *pmeth, *pres;
/* instance = module.klass( ) */
pmod = PyImport_ImportModule("module");
if (pmod == NULL) {
printf("Load Module err!\n");
return;
}
/* fetch module */
pclass = PyObject_GetAttrString(pmod, "klass");
/* fetch module.class */
Py_DECREF(pmod);
pargs = Py_BuildValue("( )");
pinst = PyEval_CallObject(pclass, pargs);
/* call class( ) */
Py_DECREF(pclass);
Py_DECREF(pargs);
/* result = instance.method(x,y) */
pmeth = PyObject_GetAttrString(pinst, "method");
/* fetch bound method */
Py_DECREF(pinst);
pargs = Py_BuildValue("(ss)", arg1, arg2);
/* convert to Python */
pres = PyEval_CallObject(pmeth, pargs);
/* call method(x,y) */
Py_DECREF(pmeth);
Py_DECREF(pargs);
PyArg_Parse(pres, "s", &cstr);
/* convert to C */
printf("%s\n", cstr);
Py_DECREF(pres);
}
/*
* PyString_Check
* PyList_Check
* PyTuple_Check
* PyDict_Check
* PyInt_Check
* PyBool_Check
* PyClass_Check
*/
void enumDict(PyObject *dict)
{
PyObject *list = PyDict_Keys(dict);
Py_ssize_t n = PyList_Size(list);
PyObject *obj = NULL;
char *key = NULL;
Py_ssize_t i = 0;
for (i = 0; i < n; i++) {
obj = PyList_GetItem(list, i);
key = PyString_AsString(obj);
PyObject *item = PyDict_GetItem(dict, obj);
if (PyInt_Check(item)) {
printf("%s: %ld\n", key, PyInt_AsLong(item));
}
else if (PyString_Check(item)) {
printf("%s: %s\n", key, PyString_AsString(item));
}
Py_DECREF(obj);
}
Py_DECREF(list);
}
void globalVars()
{
PyRun_SimpleString("result = 5 ** 2");
PyObject *module = PyImport_AddModule("__main__"); // borrowed reference
assert(module); // __main__ should always exist
PyObject *dictionary = PyModule_GetDict(module); // borrowed reference
assert(dictionary); // __main__ should have a dictionary
PyObject *result = PyMapping_GetItemString(dictionary, "result"); // borrowed reference
assert(result); // just added result
assert(PyInt_Check(result)); // result should be an integer
long result_value = PyInt_AS_LONG(result); // already checked that it is an int
printf("%ld\n", result_value);
}
void parseBool()
{
PyObject *module;
PyObject *dict;
PyObject *trueVal, *falseVal;
PyRun_SimpleString("trueVal = True\nfalseVal = False");
module = PyImport_AddModule("__main__");
dict = PyModule_GetDict(module);
trueVal = PyMapping_GetItemString(dict, "trueVal");
falseVal = PyMapping_GetItemString(dict, "falseVal");
assert(trueVal);
if (Py_True == trueVal) {
printf("True val.\n");
}
assert(falseVal);
if (Py_False == falseVal) {
printf("False val.\n");
}
}
void useDict()
{
PyObject * module;
PyObject * dict;
PyObject * dict2;
PyObject * obj;
long lval;
PyRun_SimpleString("print 123\nddd = {'a':2, 'b':'c'}\nprint ddd");
module = PyImport_AddModule("__main__");
dict = PyModule_GetDict(module);
obj = PyMapping_GetItemString(dict, "ddd");
if (obj != NULL)
{
enumDict(obj);
}
else
{
printf("Object not found\n");
} /* if */
}
int main()
{
Py_Initialize();
//loadModule();
parseBool();
useDict();
Py_Finalize();
return 0;
}
@bsrc
Copy link

bsrc commented Jun 7, 2020

I am working on a project which is related to object detection and ocr. I am using Ubuntu 18.04 and python 2.7, yolov3 for object detection and tesseract 5.0.0-alpha-692-g62ea for ocr. I have to embed python code that is for ocr into the c code which is for object detection. I wrote this C code and compile at the terminal by " sudo gcc code.c -lpython2.7 "

#include </usr/include/python2.7/Python.h>

int main() {
Py_Initialize();
PyRun_SimpleString("import sys; sys.path.append('.')");
PyRun_SimpleString("import ocr3;");
PyRun_SimpleString("print ocr3.myabs(2.0)");
Py_Finalize();

return 0;
}

but it gives an error while running a.out:

ImportError: numpy.core.multiarray failed to import
Traceback (most recent call last):
File "", line 1, in
File "./ocr3.py", line 1, in
import cv2
File "/home/asus/.local/lib/python2.7/site-packages/cv2/init.py", line 3, in
from .cv2 import *
ImportError: numpy.core.multiarray failed to import
Traceback (most recent call last):
File "", line 1, in
NameError: name 'ocr3' is not defined

so, I tried another C code:

#include <stdio.h>
#include <ncurses.h>
#include </usr/local/include/python2.7/Python.h>

int main()
{
char filename[] = "ocr3.py";
FILE* fp;

Py_Initialize();

fp = _Py_fopen(filename, "r");
PyRun_SimpleFile(fp, filename);

Py_Finalize();
return 0;

}
but again I have an issue while running a.out: " code.c:(.text+0x3e): undefined reference to `_Py_fopen' "

Unfortunately, I could not find any solution. Could you help about the fix one of the these problems?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment