我正在尝试使用C ++应用程序中的嵌入式Python。具体来说,我希望C ++启动一些PyTorch代码。
我正在Python中做一些初始化功能来执行设备(CPU或GPU)的发现,并希望将其传递回C ++代码。 C ++将调用另一个Python函数进行推断,这是C ++将设备传递给Python的时间。
pFunc_init = PyObject_GetAttrString(pModule, "torch_init");
if (pFunc_init && PyCallable_Check(pFunc_init)) {
pValue_device = PyObject_CallObject(pFunc_init, pArgs);
if (pArgs != NULL)
Py_DECREF(pArgs);
if (pValue_device != NULL) {
pFunc_infer = PyObject_GetAttrString(pModule, "torch_infer");
if (pFunc_infer && PyCallable_Check(pFunc_infer)) {
//
// TODO put object pValue_device into pArgs_device.
//
pValue_infer = PyObject_CallObject(pFunc_infer, pArgs_device);
if (pValue_infer != NULL) {
printf("Result pValue_infer: %ld\n", PyLong_AsLong(pValue_infer));
Py_DECREF(pValue_infer);
}
}
Py_DECREF(pValue_device);
}
else {
Py_DECREF(pFunc_init);
Py_DECREF(pModule);
PyErr_Print();
fprintf(stderr, "Call failed\n");
return 1;
}
}
TODO标记了我想放置此代码的位置。使用简单的Python对象,我想我知道我需要什么,但是如何处理此自定义Python对象呢?
答案 0 :(得分:1)
您可以定义一个Python函数“ detect_device”,该函数返回一个字符串,例如“ cuda”或“ cpu”。之后,在C ++代码中,您可以执行以下操作。
PyObject *detect_device, *pArgsDevice;
detect_device = PyObject_GetAttrString(pModule, "detect_device");
deviceObject = PyObject_CallObject(detect_device, NULL);
pArgsDevice = NULL;
pArgsDevice = PyTuple_New(1);
PyTuple_SetItem(pArgsDevice, 0, deviceObject);
PS:由于紧急原因,急忙写答案。很快会添加说明,但是我认为,如果您理解所编写的代码,那么您将能够理解。让我在评论中了解您的进度。