Tom*_*ear 0 c++ string assembly pointers
对于使用C++工作的装配专家来说,这是一个理论问题.我经常想要从函数中的局部变量返回一个字符串(char*或wchar*).如您所知,由于局部变量失去了范围,因此无法完成此操作.这让我很好奇,是否可以从函数中推送存储在此位置的数据?
让我说明一下:
char *IllegalFunc()
{
char *ret = "Hello World";
return ret; //warning: returning the adress of a local variable
}
//what we are attempting
char *IllegalAndMostlyIllogicalFunc()
{
char *ret = "Hello World";
__asm {
//somehow copy *ret to ESP and return
}
}
char *ARightWayToDoIt()
{
char *ret = new char[12];
strcpy(ret, "Hello World");
return ret;
}
Run Code Online (Sandbox Code Playgroud)
这只是为了好奇,我不会实际使用__asm方法...我可能只是声明一个静态char*所以我可以在c#中导入这样的函数
[dllimport(...)]
string IllegalFunc();
[dllimport(...)]
string ARightWayToDoIt(); //memory leak, I would need a FreeLastString() method
Run Code Online (Sandbox Code Playgroud)
该代码不会泄漏,因为文字字符串是静态分配的.这是完全合法的返回本地指针,而不是指针,以本地人.但是,您可以请求托管用户将返回值传递给您编写的自由函数,然后您可以使用malloc-或new.