c++ - 如何将所有权从 C++ std::vector<char> 转移到 char *pointer

标签 c++ pybind11

我遇到过这样的情况,我得到一个 std::vector<char>第三方库输出的数据,是一个非常大的长度数据,然后我需要把它转换成pybind11::array对象,我不想分配内存并执行 memcpy ,那根本没有效率。

现在我知道我可以获得 std::vector<char>缓冲区地址,但我不知道如何释放 vector 的所有权,因此当 vector 对象被破坏时缓冲区不会释放,我想知道是否有办法实现这一点。

我在下面写了一个测试代码来测试,但是失败了

#include<vector>
#include<iostream>
int *got_vec(int len){// the len in actually scene is decided by the thirdparty lib

  std::vector<int> vec;
  for(int i =0;i<len;i++){
    vec.push_back(i);
  }
  int *p_vec = &vec[0];
  std::move(vec);
  return p_vec;
}

int main(int argc,const char **argv){
  int len=atoi(argv[1]);

  std::cout<<"will go allocate memory size:"<<len<<", before allocation"<<std::endl; 

  int *p_vec = got_vec(len);
  std::cout<<"after allocation, go to print value"<<std::endl; 
  for(int i = 0; i < len;i++)
   std::cout<<p_vec[i]<<",";
  std::cout<<std::endl;

  delete p_vec;
  std::cout<<"deleted"<<std::endl;
}

程序崩溃于 std::cout<<p_vec[i]<<",";

最佳答案

std::vector 不允许分离底层缓冲区。你也可以看看taking over memory from std::vector对于类似的问题。

关于c++ - 如何将所有权从 C++ std::vector<char> 转移到 char *pointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60429385/

相关文章:

c++ - 创建一个可以在不进行实验的情况下改变类型的管道::any

c++ - 在 Linux 中清理无限循环应用程序的正确方法是什么?

c++ - 使用月份值计算过去的日期

python - 如何使用 pybind11 从 virtualenv 运行 python 解释器?

python - 你能通过pybind11创建一个python类吗?

c++ - WinAPI:钩子(Hook)函数中的非dll数据

c++ - "no match for ' operator<< ' in ' std::operator<< '"在Linux下编译时出错,VS不会出现这个错误

python - pybind11 中具有动态返回类型的函数

python - Pybind11:创建数据的 numpy View

python - 取得引用的 Eigen3 矩阵的所有权