通过dll边界的C字符串 [英] C string through dll boundaries
本文介绍了通过dll边界的C字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们需要以安全的方式通过dll边界返回一个C字符串!我们该怎么做?
We need to return a C string through dll boundaries in a safe way! How can we do this?
我的想法:
extern "C" __declspec(dllexport) const char *const Api
{
...
static const char *output = result.c_str();
return output;
}
推荐答案
正在返回指针
如果结果变量(std :: string?)在堆栈中,则为函数返回时指针将被破坏,返回的指针将悬空-当然不是您想要的。
If the result variable (std::string?) is on the stack, it's going to be destroyed when the function returns and the returned pointer will be dangling -- certainly not what you want.
一种安全的方法是strdup()响应,但调用者将负责释放C字符串。卸载DLL意味着返回的指针将悬空,除非它指向堆变量。
A safe way to do this is to strdup() the response, but then the caller will be responsible for freeing the C string. Unloading the DLL means that the returned pointer will be dangling unless it's pointing to a heap variable.
这篇关于通过dll边界的C字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文