从函数返回char数组

时间:2013-09-14 00:26:15

标签: c++ pointers boost memory-mapped-files

我有以下内容:

#include <boost\interprocess\mapped_region.hpp>
#include <boost\interprocess\file_mapping.hpp>

using namespace std;

void GetFileContents(const char* FilePath, size_t& size, char* data);

int main(){
    char* data = 0;
    const char* FilePath = "My\\Path\\File";
    size_t size = 0;
    GetFileContents(FilePath, size, data);
    //Now data is incorrect
    return 1;
}

void GetFileContents(const char* FilePath, size_t& size, char* data){
    file_mapping fm(FilePath, read_only);
    mapped_region region(fm, read_only);
    data = static_cast<char*>(region.get_address());
    //data is correct here
    size = region.get_size();
}

GetFileContents()data中包含正确的信息。但是,dataGetFileContents()返回后,它什么都没有。我做错了什么?

另外,有没有办法删除static_cast

2 个答案:

答案 0 :(得分:1)

在此功能中:

void GetFileContents(const char* FilePath, size_t& size, char* data){
    file_mapping fm(FilePath, read_only);
    mapped_region region(fm, read_only);
    data = static_cast<char*>(region.get_address());
    ...
}

fmregion是具有自动存储持续时间的对象,其生命周期在执行超出范围时结束。在这些对象被破坏后使用它们的内部结构会产生未定义的行为

另一个问题是你实际上是在尝试更改指针本身,这意味着你的函数应该char** dataPtr,你应该调用GetFileContents(FilePath, size, &data);

但是由于你使用的是C ++,你应该考虑使用std::string,或者因为你没有使用以null结尾的字符串,std::vector<char>可能更合适:

void GetFileContents(const char* FilePath, std::vector<char>& content){
    file_mapping fm(FilePath, read_only);
    mapped_region region(fm, read_only);
    content.resize(region.get_size());
    char* src = static_cast<char*>(region.get_address());
    memcpy(&content[0], src, content.size());
}

答案 1 :(得分:1)

此时数据正确的唯一原因是因为它现在指向region.get_address()所指向的任何内容。当GetFileContents()返回时,fm和region会被破坏,因为它们会丢失范围。

您需要做的是将region.get_address()中的数据复制到数据中。

size = region.get_size()
memcpy(data, region.get_address(), size)

在此之前,您需要预先分配数据(例如在main中)或以某种方式返回数据(实际返回它或通过引用/指针传递它)并在GetFileContents()中分配它。

假设您在调用GetFileContents之前已将数据分配给size_t大小,则可以执行以下操作:

char* GetFileContents(...) {
  ...
  memcpy(data, region.get_address(), size)
  size = region.get_size()
  ...
  return data
}


int main() {
  ...
  size_t fileSize = 1024; //maximum size
  char* data = new char[fileSize];
  GetFileContents("file.dat", fileSize, data)
  // now fileSize is the real file size
  ...
}
相关问题