c++ - 如何在 std::shared_ptr<uint8_t> 之间设置/获取 unsigned char *?

标签 c++ c++11 pointers

我想设置unsigned char*数据至std::shared_ptr<uint8_t>并将该指针传递给一个函数,并且在该函数中我想得到 unsigned char*数据来自std::shared_ptr<uint8_t> .

实际上我想读取图像数据如下。

FILE *fp=fopen("/data/FR/AjayPatil.jpg","rb");
if(fp)
{
    fseek(fp, 0, SEEK_END);
    data_size=ftell(fp);
    fseek(fp, 0, SEEK_SET);
    jdata=( unsigned char *)malloc(data_size+1);
    if (!jdata)
    {
        fclose(fp);
        return;
    }
    fread(jdata, data_size, 1, fp);
    fclose(fp);
}

现在我的数据在 jdata如你所见。 那么如何将这些数据复制到 std::shared_ptr<uint8_t>

我的图像结构如下。

  typedef struct Image 
  {
       uint16_t width;
       uint16_t height;
       uint8_t depth;
       std::shared_ptr<uint8_t> data;
  }             

成功复制数据后,以下操作是取回数据的正确方法吗?

     unsigned char *imagedata=data.get(); // here data means std::shared_ptr<uint8_t> data;

最佳答案

image的数据成员 data下面的代码是一个空的 std::shared_ptr<uint8_t> (没有要管理的对象):

Image image;

设置要管理的对象

通过调用 std::shared_ptrreset()您可以将托管对象设置为成员函数 jdata指向:

image.data.reset(jdata, free);

请注意,您必须提供 free作为删除器,因为 jdata 指向的数据通过 malloc 分配:

jdata=(unsigned char *)malloc(data_size+1);

未提供free因为删除会导致 delete (即:默认删除器)在data处使用的破坏。

获取托管对象

为了获取指向托管对象的指针,您可以调用 std::shared_ptrget()成员函数:

auto imagedata=data.get(); 

关于c++ - 如何在 std::shared_ptr<uint8_t> 之间设置/获取 unsigned char *?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46216348/

相关文章:

c# - 将 dll 方法从 C++ 导出到 C#。为什么我需要 : "extern "C" "

c++ - 为什么类级别的 typedef 不从模板继承?

c++ - 简单地重命名 cpp 中的文件,无需在其中写入任何内容

c - 当我们使用 array[i,j] 访问 c 中的元素时会发生什么?

c++ - Qt 或任何其他语言。事件循环

c++ - 手动解锁 lock_guard 是未定义的/错误的设计吗?

c++ - 概念检查器无法在 gcc 上编译,因为它是 'has no linkage'

c++ - 如何在支持 C++11 的 Windows 上安装 64 位 Qt?

c - C 中变量和内存概念的重用

c++ - C++ 字符串返回和 c_str() 转换的令人困惑的行为