Python Forum
Thread Rating:
  • 2 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Embedded python in C
#1
Hi all,

I am currently writing a program in C where I need to embed a python script as it is part of a testbench that will be comparing many implementation of Datalog in various language. Beside the point.

I have been following this documentation (section 5.3) for an example of how to embed a script into C via calling a function. The example uses input arguments to get the information but I will be needing to hardcode the filenames etc so I have the various properties hardcoded into char* etc.

My current implementation boils down to

Quote://globals
char* python_script_file = "python_queens.py";

//in my run benchmark function
Py_Initialize(); //init python

PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;

pName = PyString_FromString(python_script_file); //prepare file path

pModule = PyImport_Import(pName); <<< CULPRIT

--** the rest of the implementation is commented out as it crashes on the above line **--

Py_Finalize();


I am getting the following memory error:

Quote: “./TARS” terminated by signal SIGSEGV (Address boundary error)

The script is called python_queens.py and resides in the same directory as the executable. I have tried both

Quote: char* python_script_file = "python_queens.py";

and

Quote: char* python_script_file = "python_queens";

As I was not sure if the file extension needed to be included. I am quite sure it has to do with the filename I am passing in but I am not sure what I am missing.

Any help would be appreciated.

Cheers

I have since tried this example and also had it seg fault on me. I copied his exact two file and made the following CMake file for it but it still does not work.

Quote:project(pythontest)
cmake_minimum_required (VERSION 3.4 FATAL_ERROR)
set(CMAKE_BUILD_TYPE Debug)

#packages
find_package(PythonLibs 2.7 REQUIRED)

set(PYTHON_EXECUTABLE "/usr/bin/python2.7")
set(PYTHON_INCLUDE_DIR "/usr/include/python2.7")
set(PYTHON_LIBRARIES "/usr/lib/x86_64-linux-gnu/libpython2.7.so")

#includes
include_directories(${PYTHON_INCLUDE_DIRS})

#source files
file(GLOB SOURCES "*.c")

add_executable(call_function ${SOURCES})
target_link_libraries(call_function ${PYTHON_LIBRARIES})

Executing via
Quote:./call_function py_function multiply
Reply
#2
Found the solution here.
Quote:There were several problems with your code:

Py_Initialize() was not called.
PyImport_ImportModule() failed to find your python file, since in embedded Python you start without an initial module, relative to which the search can work. The fix is to explicitly include the current directory in sys.path.
"(O)" in Py_BuildValue() should use a capital 'O'.
The printlist function should return a value (since that is what the C-code expects).
This should work:


main.c
#include <Python.h>

void initPython()
{
Py_Initialize();
PyObject *sysmodule = PyImport_ImportModule("sys");
PyObject *syspath = PyObject_GetAttrString(sysmodule, "path");
PyList_Append(syspath, PyString_FromString("."));
Py_DECREF(syspath);
Py_DECREF(sysmodule);
}

int callModuleFunc(int array, size_t size) {
PyObject *mymodule = PyImport_ImportModule("py_function");
assert(mymodule != NULL);
PyObject *myfunc = PyObject_GetAttrString(mymodule, "printlist");
assert(myfunc != NULL);
PyObject *mylist = PyList_New(size);
for (size_t i = 0; i != size; ++i) {
PyList_SET_ITEM(mylist, i, PyInt_FromLong(array[i]));
}
PyObject *arglist = Py_BuildValue("(O)", mylist);
assert(arglist != NULL);
PyObject *result = PyObject_CallObject(myfunc, arglist);
assert(result != NULL);
int retval = (int)PyInt_AsLong(result);
Py_DECREF(result);
Py_DECREF(arglist);
Py_DECREF(mylist);
Py_DECREF(myfunc);
Py_DECREF(mymodule);
return retval;
}

int main(int argc, char *argv)
{
initPython();
py_function.py
'''py_function.py - Python source designed to '''
'''demonstrate the use of python embedding'''

def printlist(mylist):
print mylist
return 0
 
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to run detectron2, as python embedded code in C++, on GPU? hassaniqbal931 3 1,083 Nov-02-2023, 04:45 PM
Last Post: blabling2
  Adding libraries to embedded Python as a ZIP The_Oman 0 1,224 May-05-2023, 04:05 PM
Last Post: The_Oman
Bug Embedded Python Memory Leaks Alexei 1 1,025 Sep-16-2022, 01:15 PM
Last Post: Alexei
  Embedded Python in C++ Xeno 19 3,520 Aug-03-2022, 07:29 AM
Last Post: Gribouillis
  Embedded python fails to compile on Raspberry Pi tryfon 2 3,467 Dec-22-2020, 02:06 PM
Last Post: tryfon
  Can Embedded Python run any shared library on Android ? sprotz 0 2,307 Nov-08-2020, 12:21 PM
Last Post: sprotz
  memory leak on embedded python in c++ asdf3721 3 3,372 Jul-16-2020, 06:33 AM
Last Post: Gribouillis
  Embedded Python PyObject_CallObject function JRHeisey 1 2,375 Nov-27-2019, 01:50 AM
Last Post: casevh
  Trying to implement Python into embedded OS thesurya7 2 2,392 Apr-02-2019, 06:38 PM
Last Post: ebolisa
  Multiple calls to Python interpreter embedded in C++ application yield segmentation f mmoelle1 0 2,823 Mar-21-2019, 08:54 PM
Last Post: mmoelle1

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020