【问题标题】:How to extract values from boost::python::list to C++如何从 boost::python::list 中提取值到 C++
【发布时间】:2013-10-21 18:48:12
【问题描述】:

我正在 linux 中创建 .so 文件,以便我可以将它们导入 python 脚本并开始使用它们。我需要将数据从 python 传递到 c++ 层,以便我可以使用它们。尽管参考了许多帖子,但我无法提取这些值。我在下面给出了参考代码。 u8 => 无符号字符

#include "cp2p_layer.h"

#include <boost/python.hpp>
using namespace boost::python;

BOOST_PYTHON_MODULE(cp2p_hal)
{
    class_<SCSICommandsB>("SCSICommandsB")
        .def("Write10", &SCSICommandsB::Write10)
    ;
}

以下代码来自 cp2p_layer.cpp。我可以得到列表的长度,但数据总是黑色的

u16 SCSICommandsB::Write10 (u8 lun, u8  config, u32 LBA, u16 transferLen, u8 control, u8 groupNo,  boost::python::list pythonList)
{
    u16 listLen;
    u8*  pDataBuf = new u8[transferLen];

    listLen = boost::python::len(pythonList);
    if( listLen != transferLen)
    {
        cout<<"\nwarning: The write10 cdb has transfer length "<<transferLen<<"that doesnt match with data buffer size "<<listLen<<"\n";
    }

    for(int i = 0; i < listLen; i++)
    {
        pDataBuf[i] = boost::python::extract<u8>( (pythonList)[i] );
        cout<<boost::python::extract<u8>( (pythonList)[i] )<<"-";
        //cout<<pDataBuf[i]<<".";
    }
    cout<<"\n";
    cout<<"info: inside write10 boost len:"<<listLen<<"\n";

    return oScsi.Write10 (lun, config, LBA, transferLen, control, groupNo,  pDataBuf);
}

当我执行 python 脚本时

#!/usr/bin/python
import cp2p_hal

scsiCmds = cp2p_hal.SCSICommandsB()
plist = [0,1,2,3,4,5,6,7,8,9]
print len(plist)
scsiCmds.Write10(0,0,0,10,0,0,plist) 

输出为

10
--------        -
info: inside write10 boost len:10

非常感谢任何帮助。一旦我们执行了读取命令,我也有关于如何从 c++ 层读取数据的问题。完成此操作后,我将创建一个新帖子。提前致谢。

【问题讨论】:

    标签: c++ python linux boost


    【解决方案1】:

    问题仅在于您打印的值。 C++中的u8unsigned charcout会输出对应的ASCII字符。您的字符 (0-9) 是不可打印的,除了 ASCII 9,它恰好是一个制表符。这解释了输出中最后一个连字符之前的空格。

    如何解决?在输出前转换为 int:

    cout << static_cast<int>(boost::python::extract<u8>(pythonList[i])) << "-";
    

    【讨论】:

    • 感谢彼得的解释,这是有道理的。以十六进制打印是有意义的。似乎我们需要从 python 获取值作为 int,然后我们需要根据我们的要求进行类型转换。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 2017-09-14
    • 2016-03-15
    • 2013-07-19
    相关资源
    最近更新 更多