Return 从库到应用程序的指针

Return pointer from the library to app

所以,我有一个 lib 文件,其中包含将字符串转换为 char* 的函数:

void Additional::str2Char(string s,char** cstr)
{
    *cstr = new char[s.length() + 1];
    *cstr = (char*) s.c_str();
}

然后,我创建控制台应用程序,然后执行以下操作:

int main()
{
    Additional *a = new Additional();
    string b = "fdfd";
    char *test;
    a->str2Char(b, &test);
    cout << test << endl;
    delete a;
}

输出真的很糟糕.. 帮帮我,我不知道如何从 lib 中正确获取指针。

首先你分配一些内存。

然后您重新分配指向该内存的指针,指向本地字符串的内容s,泄漏您分配的内存。

然后你 return 从函数中销毁 s,让指针悬空。它不再指向有效数据,取消引用它会产生未定义的行为。

最好的解决方案是停止使用指针和 new,并为所有字符串使用 std::string。如果你真的想这样做,那么你需要将字符串内容复制到新内存中:

*cstr = new char[s.length() + 1]; // no change
std::strcpy(*cstr, s.c_str());    // copy the data, including the terminator

如果图书馆不打算修改文本,那么 c_str() 调用就足够了。无需创建 char pointer/array.

如果要修改正文:

strncpy(tab2, tmp.c_str(), sizeof(tab2));
tab2[sizeof(tab2) - 1] = 0;

由于您想在函数内部处理内存分配,因此可以使用不同的 API:

// Creates a const char* and copies the contents of s to it. Caller
// takes ownership of the returned data.
const char* str2cstr(const string& s) {
    char* cstr = new char[s.size()];
    strncopy(cstr, s.c_str(), s.size());
    return cstr;
}

现在您可以做到 const char* cstr = str2cstr(str);。另请注意,我正在使用 const string& 参数来避免额外的字符串复制。