C ++和Boost.Python-如何将变量公开给python并在循环中更新?

问题描述 投票:0回答:1

简介

我有一个使用boost.python包从c ++调用的python代码。当从.py调用MyFunc时,我可以传递一些变量,如下所示:

Py_SetPythonHome(pySearchPath);
try
{
Py_Initialize();
numpy::initialize();
object module = import("__main__");
object name_space = module.attr("__dict__");
exec(python_full, name_space, name_space);
object MyFunc = name_space["MyFunc"];

object result = MyFunc(var1, var2, var3)); //HERE

//Python results storage
numpy::ndarray ret = extract<numpy::ndarray>(result);
int input_size = ret.shape(0);
std::vector<std::vector<double>> v(input_size, std::vector<double>(50));
}
catch (error_already_set)
{
    PyErr_Print();
}

但是我需要另一个变量,让我们将其命名为var4,以基于C ++ GUI在我的python代码的每个循环上进行更新。如果我正确理解MyFunc(var1, var2, var3)在开始时仅传递一次值,那么即使我在执行后更改var1的值,也不会影响python代码。

问题

有没有办法公开c ++变量,因此它将在python代码中“实时”更新?如果全部使用一种语言,将是微不足道的(例如,使用全局变量),但是在两种环境的边缘将变得棘手。

编辑:

我试图像这样公开变量gui_cancel

BOOST_PYTHON_MODULE(cbtest)
{
    class_<callback_handler, boost::noncopyable>("callback_handler", no_init)
        .def_readwrite("gui_cancel", &callback_handler::gui_cancel);
        ;
};

但是以这种方式从python访问它:

import cbtest
holder = cbtest.callback_handler
print(holder.gui_cancel)

仅提供对象的属性:

<property object at 0x0000012D9AA90BD8>

python c++ qt boost boost-python
1个回答
0
投票

我不知道您如何直接公开变量,但是您始终可以公开C函数,并让Python脚本调用该C函数将变量的当前值返回给Python脚本。

下面是演示该技术的示例C程序。请注意,main()运行一个简单的Python脚本,该脚本调用包含的C函数GetRandomNumber()GetRandomNumber()选择一个随机数并将其值打印到stdout,然后将其返回到Python脚本。然后,Python脚本也会打印出该值,因此您可以验证Python代码所打印的值与C代码选择的值相同。

#include <Python.h>
#include <stdio.h>

static PyObject * GetRandomNumber(PyObject * pyObj, PyObject * args, PyObject * keywords)
{
   const int randomNumber = rand();
   printf("C Function GetRandomNumber():  I choose:  %i\n", randomNumber);
   return PyLong_FromLong(randomNumber);
}

static PyMethodDef DemoEditorMethods[] = {
   {"GetRandomNumber", (PyCFunction)GetRandomNumber, METH_KEYWORDS | METH_VARARGS, "Returns a random integer."},
   {NULL, NULL, 0, NULL}  // list terminator
};

PyDoc_STRVAR(demo_doc, "This module is just here to demonstrate calling a C function from Python and having it return a value.");

static struct PyModuleDef DemoModuleDefinition = {
   PyModuleDef_HEAD_INIT,
   "embedded_demo",
   demo_doc,
   -1,
   DemoEditorMethods,
   NULL,
   NULL,
   NULL,
   NULL
};

int main(int argc, char *argv[])
{
    Py_Initialize();

    // Note:  if this line is causing you link errors under Windows,,
    // try rebuilding pythoncore.lib in "Release Mode" instead of
    // "Debug mode".
    PyObject * csMod = PyModule_Create(&DemoModuleDefinition);
    if (csMod)
    {
       PyObject *modules = PyImport_GetModuleDict();
       if (modules)
       {
          PyObject * nameObj = PyUnicode_FromString("embedded_demo");
          if ((nameObj == NULL)||(PyObject_SetItem(modules, nameObj, csMod) != 0)) printf("PyObject_SetItem() failed!?\n");
       }
       else printf("PyImport_GetModuleDict() returned NULL!\n");
    }
    else printf("Unabled to create embedded_demo Python module!\n");

    if (PyImport_ImportModule("embedded_demo") == NULL) printf("Unable to import embedded_demo Python module!\n");

    PyRun_SimpleString(
        "import sys;"
        "import embedded_demo;"
        "v = embedded_demo.GetRandomNumber();"
        "print('Python Script:  The random value I got from the C GetRandomNumber() function is: %i' % v);"
    );
    Py_Finalize();
    return 0;
}

当我运行上述程序时,我看到此输出:

$ ./test_c_function_call
C Function GetRandomNumber():  I choose:  16807
Python Script:  The random value I got from the C GetRandomNumber() function is: 16807
© www.soinside.com 2019 - 2024. All rights reserved.