繁体   English   中英

将 Python object 传递给 C 并再次返回

[英]Pass Python object to C and back again

我正在尝试从 C++ 应用程序中使用嵌入式 Python。 具体来说,我希望我的 C++ 启动一些 PyTorch 代码。

我正在 Python 中进行一些初始化 function 以执行设备(CPU 或 GPU)发现,并希望将其传递回 C++ 代码。 The C++ will call another Python function for inference which is when the C++ will pass the device to 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 object?

您可以定义一个 Python function “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:由于一些紧迫性,匆忙写了答案。 将很快添加解释,但我认为如果您理解您编写的代码,您将能够理解这一点。 在评论中让我知道您的进度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM