如何从 boost::p ython::list 中提取值到C++

How to extract values from boost::python::list to C++

本文关键字:提取 C++ list ython boost      更新时间:2023-10-16

我正在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++中的u8是一个unsigned charcout将输出相应的ASCII字符。 您的字符 (0-9) 不可打印,ASCII 9 除外,它恰好是一个制表符。 这解释了输出中最后一个连字符之前的空格。

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

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