【问题标题】:Is it possible to get a raw pointer to std::vector<unsigned int> data? [duplicate]是否可以获得指向 std::vector<unsigned int> 数据的原始指针? [复制]
【发布时间】:2014-06-02 23:09:04
【问题描述】:

我有一个 std::vector ,它将填充一些专有硬件的指令。我有代码来构造这个缓冲区并很好地操作它。

问题是我需要使用另一个库(基于 C)来构建类似的专有硬件指令,但是库希望我们提供原始内存并返回一个指向它的指针,然后库使用它来编写它的命令。

我想完成类似以下的事情[伪代码,不像真正的代码]:

    void* theLibraryCallback (void* clientData, unsigned int theLibrarySize)
    {
        std::vector<unsigned int> cmd = reinterpret_cast<std::vector<unsigned int>>(clientData);
        std::vector<unsigned int>::size_type cmdSize = cmd->size();

        for (int loop=0;loop<theLibrarySize; loop++)
            cmd->push_back(0xdeadbeef);

        return cmd->GET_RAW_POINTER_AT(sizeof(unsigned int)*cmdSize);   ///<< How can I do this?
    }

概念是我向向量添加值以腾出空间,但其他库直接修改它们。

如果我不能这样做,我必须考虑分配临时原始内存,用库填充它,然后将其复制到我的向量中,但如果可能的话,我想避免这种情况。

我想做的事有可能吗?

【问题讨论】:

    标签: c++ vector


    【解决方案1】:

    所以两件事:

    1. 您可以使用std::vector::data()&amp;vec.front() 访问向量的连续内存。

    2. 如果您在上面显示的代码中执行此操作,您将返回一个指向数据的指针,该指针会在函数返回时消失(向量的析构函数将运行,数据将被释放)。

    【讨论】:

    • 我的意思是让 cmd 成为一个指针,我将在伪代码中进行编辑,所以很多人不要评论太多,干杯
    • 我以前从来没有这样做过,尽管我已经使用向量多年,但很奇怪......我从来不知道 ::data(),这正是我所需要的。跨度>
    【解决方案2】:

    我假设clientData 是一个用户定义的值,您已将其设置为指向您已在其他地方分配的vector 的指针,并确保它在 C 库写入时在内存中保持活动状态它。如果是这样,您可以在回调中执行此操作:

    void* theLibraryCallback (void* clientData, unsigned int theLibrarySize)
    {
        std::vector<unsigned int> *cmd = reinterpret_cast<std::vector<unsigned int> *>(clientData);
        std::vector<unsigned int>::size_type cmdSize = cmd->size();
    
        for (int loop=0;loop<theLibrarySize; loop++)
            cmd->push_back(0xdeadbeef);
    
        return &(*cmd)[cmdSize];
    }
    

    您可能需要考虑使用typedef 使向量访问更易于阅读:

    typedef std::vector<unsigned int> uintvec;
    
    void* theLibraryCallback (void* clientData, unsigned int theLibrarySize)
    {
        uintvec *cmd = reinterpret_cast<uintvec*>(clientData);
        uintvec::size_type cmdSize = cmd->size();
    
        for (int loop=0;loop<theLibrarySize; loop++)
            cmd->push_back(0xdeadbeef);
    
        return &(*cmd)[cmdSize];
    }
    

    【讨论】:

      猜你喜欢
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多