본문 바로가기
카테고리 없음

[파이썬] Interfacing C++ and Python with the Python API

by 나스닥171819 2024. 10. 30.
728x90
반응형

파이썬을 c++ 에 내장하여 사용할 수가 있다.

 

 

저수준으로 제어해야 반환값을 받을 수 있다.

 

simple.py 를 실행한 결과를 볼 수 있다.

 

https://www.codeproject.com/Articles/5365450/Interfacing-Cplusplus-and-Python-with-the-Python-A.

 

Interfacing C++ and Python with the Python API

This article explains how the Python API makes it possible to embed Python in C++ and write extension modules in C++ that can be imported in Python.

www.codeproject.com

#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <iostream>

int main() {

    PyObject* module, * func, * args, * ret;

    // Initialize python access
    Py_Initialize();

    // Import the simple.py code
    module = PyImport_ImportModule("simple");
    if (module) {

        // Access the attribute named plus
        func = PyObject_GetAttrString(module, "plus");

        // Make sure the attribute is callable
        if (func && PyCallable_Check(func)) {

            // Create a tuple to contain the function's args
            args = PyTuple_New(2);
            PyTuple_SetItem(args, 0, PyLong_FromLong(4));
            PyTuple_SetItem(args, 1, PyLong_FromLong(7));

            // Execute the plus function in simple.py
            ret = PyObject_CallObject(func, args);
            Py_DECREF(args);
            Py_DECREF(func);
            Py_DECREF(module);

            // Check the return value
            if (ret) {

                // Convert the value to long and print
                long retVal = PyLong_AsLong(ret);
                std::cout << "Result: " << retVal << std::endl;
            }
            else {

                // Display error
                PyErr_Print();
                std::cerr << "Couldn't access return value" << std::endl;
                return 1;
            }
        }
        else {

            // Display error
            if (PyErr_Occurred())
                PyErr_Print();
            std::cerr << "Couldn't execute function" << std::endl;
        }
    }
    else {

        // Display error
        PyErr_Print();
        std::cerr << "Couldn't access module" << std::endl;
        return 1;
    }

    // Finalize the Python embedding
    Py_Finalize();
    return 0;
}

반응형