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

时间:2015-12-30 19:38:16

标签: python c++ pointers boost-python ros

我在c ++中有一个返回向量的函数。我正在使用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

1 个答案:

答案 0 :(得分:0)

在您的情况下,您尝试在intshared_ptr之间进行错误的转换:

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

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

您可以定义自己的空删除 void 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());