簡體   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