在C+中嵌入python串行控制器+;
我已经搜索了好几个小时,试图让这段代码正常工作,但我似乎不太明白 我正在研究C++中的函数,我可以调用许多python脚本中的一个,它们有不同数量的争论。Python工作,但我在C++中不断地获得分段错误。p>在C+中嵌入python串行控制器+;,python,c++,interface,serial-port,Python,C++,Interface,Serial Port,我已经搜索了好几个小时,试图让这段代码正常工作,但我似乎不太明白 我正在研究C++中的函数,我可以调用许多python脚本中的一个,它们有不同数量的争论。Python工作,但我在C++中不断地获得分段错误。p> double run_python(motor_command command){ //A routine that will run a python function that is in the same directory. Py_Initialize();
double run_python(motor_command command){
//A routine that will run a python function that is in the same directory.
Py_Initialize();
PySys_SetPath(".");
string pyName; //Declaration of the string and int
int speed;
if (command.action == READ){
pyName = "read_encoders"; //Name of one python module
}else{
pyName = "drive_motor"; //Name of the other python module
speed = command.speed; //struct
}
int board_address = command.board_address;
int motor = command.motor_num;
//PyObject* moduleName = PyString_FromString(pyName.c_str());
// Py_INCREF(myModule);
//PyObject* myFunction = PyObject_GetAttrString(myModule, "run"); //Both of these python functions have subroutine 'run'
PyObject* args;
if(command.action == READ){
args = PyTuple_Pack(2,PyInt_FromLong(board_address),PyInt_FromLong(motor)); //Appropriate args for the read_encoders
}else{
args = PyTuple_Pack(3,PyInt_FromLong(board_address),PyInt_FromLong(motor), PyInt_FromLong(speed)); //Appropriate args for the drive_motor
}
Py_INCREF(args);
cout << "I got here" << endl;
PyObject* myModule = PyImport_Import((char*)pyName.c_str());//Python interface
cout << "args = " << args << " modlue = " << myModule << endl;
//Py_INCREF(myModule);
PyObject* myResult = PyObject_CallObject(myModule, args); //Run it and store the result in myResult
Py_INCREF(myResult);
double result = PyFloat_AsDouble(myResult);
Py_DECREF(myResult);
return result;
}
提前谢谢你!如果你有任何其他的方法可以让它以同样的方式工作,我欢迎你的建议 尝试将此代码追加。到您的sys.path:
PyObject *sys_path;
PyObject *path;
sys_path = PySys_GetObject("path");
path = PyString_FromString(".")
if (PyList_Append(sys_path, path) < 0)
PyObject*sys\u路径;
PyObject*路径;
sys_path=PySys_GetObject(“路径”);
path=PyString\u FromString(“.”)
if(PyList_Append(sys_path,path)<0)
资料来源:
旧的:
首先,尝试单独执行Python脚本,并在命令行上使用Python。
从C/C++程序调试Python错误比较困难。您安装pySerial了吗?您说是另一种方式吗?好删除C++位可能会解决这个问题。为什么不只用Python实现呢?哈哈,我希望如此。这是一个设计要求。正如问题中所提到的,是的,python本身可以完美地工作,包括pySerial。我认为问题出在PySys_SetPath(“.”)上;我想它清除了你的模块路径。我正在检查文件。。。
PyObject *sys_path;
PyObject *path;
sys_path = PySys_GetObject("path");
path = PyString_FromString(".")
if (PyList_Append(sys_path, path) < 0)