文件重定位 - 不好的做法?

时间:2012-06-07 19:15:38

标签: c++

我正在使用处理数据重定位的二进制文件格式,即。指向位于文件另一部分的数据的“指针”,并在文件末尾写入双指针(保存数据指针偏移量的整数)。

我有一个std::queue<unsigned int*>来保存数据指针。以下是我如何使用它的示例(警告,丑陋的指针代码):

std::queue<unsigned int*> relocations;

struct TestData {
    unsigned int Length;
    char* Text;
    unsigned int Format;
};

void MakeData() {
    unsigned char* chunkOneData = new unsigned char[sizeof(TestData)];

    TestData* mainData = reinterpret_cast<TestData*>(chunkOneData);
    mainData->Length = this->Text.length();
    mainData->Format = this->TextFormat;

    unsigned char* chunkFiveData = new unsigned char[this->Text.length() + 1];
    strcpy(reinterpret_cast<char*>(chunkFiveData), this->Text.c_str());

    mainData->Text = reinterpret_cast<char*>(chunkFiveData);

    relocations.push(reinterpret_cast<unsigned int*>(&mainData->Text));

    dataChunks[0].Add(chunkOneData, sizeof(TestData));
    dataChunks[4].Add(chunkFiveData, this->Text.length() + 1);
}

以下是“制作”文件重定位的代码:

std::vector<unsigned int> relocationTable;
std::queue<unsigned int*> relocations;

unsigned int GetDataOffset(unsigned int *relocation) {

    for (int i = 0; i < 6; i++) {

        for (int j = 0; j < dataChunks[i].size(); j++) {
            if ((relocation >= (unsigned int*)dataChunks[i][j].data)
                && (relocation < (unsigned int*)dataChunks[i][j].data + dataChunks[i][j].size))
            {
                return ((unsigned int)relocation - (unsigned int)dataChunks[i][j].data + dataChunks[i][j].relativeOffset);
            }
        }

    }

    return 0xFFFFFFFF;
}

void MakeRelocationTable() {

    while (!relocations.empty()) {
        unsigned int* relocation = relocations.front();
        relocations.pop();

        unsigned int* relocatedData = *((unsigned int**)relocation);

        if (relocatedData != NULL) {

            unsigned int dataOffset = GetDataOffset(relocatedData);

            if (dataOffset = 0xFFFFFFFF)
                dataOffset = 0;

            *relocation = dataOffset;

            unsigned int pointerOffset = GetDataOffset(relocation);
            relocationTable.push_back(pointerOffset);
        }
    }
}

现在,告诉我你是否不同意,但这是一些可怕的代码IMO。写这篇文章让我很头疼。但似乎它是“最容易的”(但你定义简单)的方法。

无论如何我可以清理这段代码吗?或者还有其他方法可以做到这一点吗?谢谢你的帮助,

亚历

0 个答案:

没有答案