使用boost-python将参数从Python脚本传递到C ++ [英] Parameter passing from Python script to C++ with boost-python

查看:259
本文介绍了使用boost-python将参数从Python脚本传递到C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用boost-python和boost-numpy将Python嵌入C ++中. 我有以下Python测试脚本:

I am currently embedding Python in C++ using boost-python and boost-numpy. I have the following Python test script:

import numpy as np
import time


def test_qr(m,n):
    print("create numpy array")
    A = np.random.rand(m, n)

    print("Matrix A is {}".format(A))
    print("Lets QR factorize this thing! Mathematics is great !!")
    ts = time.time()
    Q, R = np.linalg.qr(A)
    te = time.time()
    print("It took {} seconds to factorize A".format(te - ts))
    print("The Q matrix is {}".format(Q))
    print("The R matrix is {}".format(R))
    return Q,R


def sum(m,n):
    return m+n

我能够像这样在C ++中执行部分代码:

I am able to execute a part of the code in C++ like this:

namespace p = boost::python;
namespace np = boost::python::numpy;
int main() {
Py_Initialize();  //initialize python environment
np::initialize(); //initialize numpy environment
p::object main_module = p::import("__main__");
p::object main_namespace = main_module.attr("__dict__");

// execute code in the main_namespace
p::exec_file("/Users/Michael/CLionProjects/CythonTest/test_file.py",main_namespace); //loads python script
p::exec("m = 100\n"
        "n = 100\n"
        "Q,R = test_qr(m,n)", main_namespace);

np::ndarray Q_matrix = p::extract<np::ndarray>(main_namespace["Q"]); // extract results as numpy array types
np::ndarray R_matrix = p::extract<np::ndarray>(main_namespace["R"]);
std::cout<<"C++ Q Matrix: \n" << p::extract<char const *>(p::str(Q_matrix)) << std::endl; // extract every element as a
std::cout<<"C++ R Matrix: \n" << p::extract<char const *>(p::str(R_matrix)) << std::endl;
std::cout<<"code also works with numpy, ask for a raise" << std::endl;
p::object sum = main_namespace.attr("sum")(10,10);
int result = p::extract<int>(main_namespace.attr("sum")(10,10));
std::cout<<"sum result works " << result << std::endl;
return 0;}

现在,我正在尝试在Python脚本中使用sum函数,但我并不总是想编写类似以下的字符串:

Now I am trying to use the sum function in the Python script but I do not always want to write a string like:

p::exec("m = 100\n"
        "n = 100\n"
        "Q,R = test_qr(m,n)", main_namespace);}

如何在不使用exec函数的情况下完成此操作?

How can this be done without using the exec function?

我尝试过类似的事情:

p::object sum = main_namespace.attr("sum")(10,10);
int result = p::extract<int>(main_namespace.attr("sum")(10,10));
std::cout<<"sum result works " << result << std::endl;

如boost文档中所述. 我也尝试使用call_method函数,但是没有用. 我得到了boost :: python :: error_already_set异常,这意味着Python中有问题,但是我不知道是什么. 或退出代码11.

As mentioned in the documentation of boost. I also tried using the call_method function, but it didn't work. I get either boost::python::error_already_set exception which mean there is something wrong in Python, but I do not know what. Or an exit code 11.

推荐答案

问题相当简单.让我们看一下您提到的教程:

The issue is rather trivial. Let's look at the tutorial you mention:

object main_module = import("__main__");
object main_namespace = main_module.attr("__dict__");
object ignored = exec("result = 5 ** 2", main_namespace);
int five_squared = extract<int>(main_namespace["result"]);

请注意他们如何提取最后一行中的result对象:main_namespace["result"]

Notice how they extract the result object in the last line: main_namespace["result"]

main_namespace对象是Python字典,而不是提取它的属性,而是在查找使用特定键存储的值.因此,使用[]进行索引编制是可行的方法.

The main_namespace object is a Python dictionary, and rather than extracting it's attribute, you're just looking for a value stored with the particular key. Hence, indexing with [] is the way to go.

C ++代码:

#define BOOST_ALL_NO_LIB

#include <boost/python.hpp>
#include <boost/python/numpy.hpp>

#include <iostream>

namespace bp = boost::python;

int main()
{
    try {
        Py_Initialize();

        bp::object module = bp::import("__main__");
        bp::object globals = module.attr("__dict__");

        bp::exec_file("bpcall.py", globals);

        bp::object sum_fn = globals["sum"];
        int result = bp::extract<int>(sum_fn(1,2));
        std::cout << "Result (C++) = " << result << "\n";

    } catch (bp::error_already_set) {
        PyErr_Print();
    }

    Py_Finalize();
}

Python脚本:

def sum(m,n):
    return m+n

输出:

Result (C++) = 3

这篇关于使用boost-python将参数从Python脚本传递到C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆