I have read few tutorial on python embedded c++. I had refer back to python object. https://docs.python.org/3/c-api/function.html
Python script:
import picamera
from pylibdmtx.pylibdmtx import decode
from time import sleep
import cv2
def test():
camera = picamera.PiCamera()
camera.start_preview()
sleep(10)
camera.stop_preview()
camera.capture('image3.png')
camera.close()
data = decode(cv2.imread('/home/pi/image3.png'))
return(data)
C++ Script
#include<Python.h>
#include<string>
int main(){
String data2;
Py_Initialize();
***Doing Some Stuff TO GET data from test() function in python script and store in variable data2
Py_Finalize();
}
I had use PyRun_SimpleString() to do before, it can work. But, it cannot pass the variable to C++. The result I want is it can store the string to the variable at C++. Example after C++ execute the python script, python function return "1234". And "1234" is store at C++ variable (data2)
Please, help me solve this problem. This is my first time python embedding c++, and have some guide please.
Again, if can please provide me solution on
***Doing Some Stuff TO GET data from test() function in python script and store in variable data2
Thanks very much.... Appreciate
If I understand correctly, you want your C++ code to call your Python test() function and get the string result of that function back so the C++ code can do something with it. If so, I think something like this would do the trick for you:
std::string data;
char fileName[] = "my_test_python_script.py";
PyObject * moduleObj = PyImport_ImportModule(filename);
if (moduleObj)
{
char functionName[] = "test";
PyObject * functionObj = PyObject_GetAttrString(moduleObj, functionName);
if (functionObj)
{
if (PyCallable_Check(functionObj))
{
PyObject * argsObject = PyTuple_New(0);
if (argsObject)
{
PyObject * resultObject = PyEval_CallObject(functionObj, argsObject);
if (resultObject)
{
if ((resultObject != Py_None)&&(PyString_Check(resultObject)))
{
data = PyString_AsString(resultObject);
}
Py_DECREF(resultObject);
}
else if (PyErr_Occurred()) PyErr_Print();
Py_DECREF(argsObject);
}
}
Py_DECREF(functionObj);
}
else PyErr_Clear();
Py_DECREF(moduleObj);
}
std::cout << "The Python test function returned: " << data << std::endl;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.