Copy data from a local pointer for return value
Heres a theoretical question for you assembly experts working in C++. I am often wanting to return a string (char * or wchar *) from a local variable within a function. As you know this cannot be done, as the local variable loses sco开发者_运维技巧pe. This gets me curious, would it be possible to push the data stored at this location from within the function?
Let me illustrate:
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;
}
This is just for curiousity, I wouldn't acctually use __asm method... I will probably just declare a static char * so i can import the function like so in c#
[dllimport(...)]
string IllegalFunc();
[dllimport(...)]
string ARightWayToDoIt(); //memory leak, I would need a FreeLastString() method
That code doesn't leak, as literal strings are statically allocated. It's perfectly legal to return local pointers, but not pointers to locals. However, you could request that the managed user passes the return value to a free function that you write, and then you can malloc- or new.
Since you're in C++, why not just return std::string?
Edit:
DeadMG points out you're importing the function from C#. The usual approach in C was to pass a character buffer into the function as an argument. From what I've read, that works here too. See, for example, this previous question.
As an assembly expert working in C++, I can assure you that in-line assembly code is totally inappropriate here :-)
I'm not an expert, but I do know that prologue and epilogue code can mess up what you want to do. If you're really doing that (which, needless to say, is bad practice), take a look at naked.
精彩评论