How to Invoke Python Function From C++

In the process of designing the swarm robotics benchmark system, a question of how to interact with robot platforms written in Python draw a lot of my attention. I have tried to wrap the entire C++ library with Cython to provide Python APIs, may be in another post later, or to provide C++ driver code that is capable of calling the Python platform API. Simply speaking, the choice between using Python programs to call c++ functions, or using c++ programs to call Python functions. I choose the later one just to keep only one C++ as user program.

Following are the sample C++ and Python program for testing.

 

#define PY_SSIZE_T_CLEAN
#include <Python/Python.h>
#include <stdio.h>

int main() {
    printf("start cpp function\n");
    
    Py_Initialize();
    
    PyObject * sys = PyImport_ImportModule("sys");
    PyObject * path = PyObject_GetAttrString(sys, "path");
    PyList_Append(path, PyString_FromString("."));
    
    PyObject * ModuleString = PyString_FromString((char*) "py_function");
    PyObject * Module = PyImport_Import(ModuleString);
    PyObject * Dict = PyModule_GetDict(Module);
    PyObject * Func = PyDict_GetItemString(Dict, "python_test");
    PyObject * Result = PyObject_CallObject(Func, NULL);
    
    Py_Finalize();
}

19 thoughts on “How to Invoke Python Function From C++

  1. e söylemek gerekirse, c++ işlevlerini çağırmak için Python programlarını kullanma veya Python işlevlerini çağırmak için c++ programları agario

  2. aşka bir gönderide olabilir veya Python platform API’sini çağırabilen C++ sürücü kodunu sağlamaya çalıştım. Basitçe söylemek gerekirse, c++ işlevlerini çağırmak için Python programlarını kullanma veya Python işlevlerini çağırmak için c++ programlarını kullanma arasındaki seçim. Kullanıcı programı olarak yalnızca bir C++ tutmak için sonrakini seçiyorum. metin2 pvp serverler

  3. In the process of designing the swarm robotics benchmark system, a question of how to interact with robot platforms written in Python draw a lot of my attention. I have tried to wrap the entire metin2 pvp serverler

  4. Ammending Python with C++ seems to be really cool. As time is travelling the complexities of coding language needs to be more simplified. As i have seen there are multiple businesses that struggle to understand all the fundamentals of it. Just look at the Amazon forums the most efficient online seller people are unable to solve common Amazon listing error codes. All the programming languages need to be more visualizing than the coding.

Leave a Reply

Your email address will not be published. Required fields are marked *