[英]Python Embedded C++
I have read few tutorial on python embedded c++. 我读过一些有关python嵌入式c ++的教程。 I had refer back to python object.
我已经参考了python对象。 https://docs.python.org/3/c-api/function.html
https://docs.python.org/3/c-api/function.html
Python script: Python脚本:
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 C ++脚本
#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. 我之前使用PyRun_SimpleString()可以工作。 But, it cannot pass the variable to C++.
但是,它不能将变量传递给C ++。 The result I want is it can store the string to the variable at C++.
我想要的结果是它可以将字符串存储到C ++的变量中。 Example after C++ execute the python script, python function return "1234".
C ++执行python脚本后的示例,python函数返回“ 1234”。 And "1234" is store at C++ variable (data2)
并且“ 1234”存储在C ++变量(data2)中
Please, help me solve this problem. 请帮我解决这个问题。 This is my first time python embedding c++, and have some guide please.
这是我第一次使用python嵌入c ++,请提供一些指南。
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 ***做一些事情从python脚本中的test()函数获取数据并存储在变量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. 如果我理解正确,则您希望C ++代码调用Python test()函数并获取该函数的字符串结果,以便C ++代码可以对其进行处理。 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.