dlopen后错误的字符串库?

时间:2016-08-16 15:31:29

标签: c++ string dlopen

我目前在模块化程序中使用dlopen,我认为有些事情确实是错误的,但我似乎无法弄明白。

requirementData是一个名为VoidData的类的向量。它只是一个容易处理void *的类

getCopyOfData()使用memcpy复制存储在void *中的数据。在此之前, voidptr 的地址与存储在我的VoidData对象中的地址不同,因此复制成功。

现在...... stringA 给了我正确的字符串。这对 stringB 也没问题。但接下来是stringC,他给了我一些奇怪的东西。

void* voidptr = requirementData[0].getCopyOfData();

string stringA = *((string*) voidptr);
cout << "VoidPtr: " << stringA << endl; // VoidPtr: 'SayHey'

string stringB = *((string*) voidptr);
cout << "VoidPtr: " << stringB << endl; // VoidPtr: 'SayHey'

// load library
void *handle = dlopen("/usr/lib64/libOpcWorkingPackage.so", RTLD_LAZY);

string stringC = *((string*) voidptr);
cout << "VoidPtr: " << stringC << endl; // VoidPtr: '����'

我还尝试将 voidptr 强制转换为uint8_t数组。每次数组给我相同的32个数字。

for (unsigned int i = 0; i < sizeof(stringC); i++){
    cout << to_string(((uint8_t*) voidptr)[i]) << ", ";
}
cout << endl;
// 80, 181, 228, 245, 255, 127, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 83, 97, 121, 101, 119, 121, 0, 0, 0, 183, 228, 245, 255, 127, 49, 52

我没有想法,也许有人可以帮助我。

谢谢,Narase

编辑:这是我的getCopyOfData()函数:

void* VoidData::getCopyOfData() const {
    void *data = malloc(size);
    memcpy(data, storedData, size);
    return data;
}

编辑:搞定了

我得到的数据是char []。这个char []放在一个不复制它们的字符串中,它只是在它上面放一个指针。释放char []后,该字符串将一直有效,直到

之后再使用内存为止

感谢您正确的想法user4581301!

1 个答案:

答案 0 :(得分:0)

我得到的数据是char []。这个char []放在一个字符串(由我)中,它不会复制它们,它只是在它上面放一个指针。释放char []后,字符串将一直有效,直到之后再使用内存为止。

感谢您正确的想法user4581301!