如何使用python将指针输入发送到c++程序

How to send pointer input to c++ program using python?

本文关键字:c++ 程序 输入 何使用 python 指针      更新时间:2023-10-16

我在c++中有一个函数,它返回vector。我使用BOOST _PYTHON_MODULE从PYTHON调用它。我想发送一个指针作为c++函数的输入。我试图将指针作为字符串发送。我知道这是最糟糕的方法,但有些人正在使用它,而且效果很好。就我而言,它不起作用。我是c++新手。

工作案例:

#include <iostream>
#include <string.h>
#include <sstream>
using namespace std;
int main(){
    string s1 = "0x7fff3e8aee1c";
    stringstream ss;
    ss << s1;
    cout << "ss : " << ss << endl;
    long long unsigned int i;
    ss >> hex >> i;
    cout << "i : " << i << endl;
    int *i_ptr=reinterpret_cast<int *>(i);
    cout << "pointer: " << i_ptr << endl;
    return 0;
}

我的案例:

#include "openrave-core.h"
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "valid_grasp_generator/GraspSnapshot.h"
#include <iostream>
#include <vector>
#include <boost/python.hpp>
#include <sstream>
using namespace OpenRAVE;
using namespace std;
boost::python::list get_penetration_depth(string env)
{
    vector<double> vec(9,0);
    stringstream ss(env);
    long long unsigned int i;
    ss >> hex >> i;
    EnvironmentBasePtr penv = reinterpret_cast<int *>(i);

    //code for getting penetration value from the openrave
    typename std::vector<double>::iterator iter;
    boost::python::list list;
    for (iter = vec.begin(); iter != vec.end(); ++iter) {
        list.append(*iter);
    }
    return list;
}
BOOST_PYTHON_MODULE(libdepth_penetration){
    using namespace boost::python;
    def("get_penetration", get_penetration_depth);
}

catkin_make:期间出错

/home/saurabh/catkin_ws/src/valid_grasp_generator/src/depth_penetration.cpp: In function ‘boost::python::list get_penetration_depth(std::string)’:
/home/saurabh/catkin_ws/src/valid_grasp_generator/src/depth_penetration.cpp:37:56: error: conversion from ‘int*’ to non-scalar type ‘OpenRAVE::EnvironmentBasePtr {aka boost::shared_ptr<OpenRAVE::EnvironmentBase>}’ requested
     EnvironmentBasePtr penv = reinterpret_cast<int *>(i);
                                                        ^
make[2]: *** [valid_grasp_generator/CMakeFiles/depth_penetration.dir/src/depth_penetration.cpp.o] Error 1
make[1]: *** [valid_grasp_generator/CMakeFiles/depth_penetration.dir/all] Error 2
make: *** [all] Error 2
Invoking "make -j8 -l8" failed

在您的案例中,您尝试了intshared_ptr:之间的错误转换

EnvironmentBasePtr penv = reinterpret_cast<int *>(i); // wrong conversion
// where EnvironmentBasePtr is boost::shared_ptr<EnvironmentBase>

对于这种转换,我建议使用shared_ptra null deleter的构造函数。我看到了3种可能的解决方案。

您可以定义自己的null deletervoid deleter(void* ptr) {},然后:

boost::shared_ptr<EnvironmentBase> penv(reinterpret_cast<EnvironmentBase *>(i),&deleter);

如果您的提升为1.55或更低,则可以包含<boost/serialization/shared_ptr.hpp>,然后:

boost::shared_ptr<EnvironmentBase> penv(reinterpret_cast<EnvironmentBase *>(i),boost::serialization::null_deleter());

如果您的提升为1.56或更高,则可以包含<boost/core/null_deleter.hpp>,然后:

boost::shared_ptr<EnvironmentBase> penv(reinterpret_cast<EnvironmentBase *>(i),boost:null_deleter());