I do have a simple test-case here (C++) which does LoadLibrary, GetProcAddress & calls the function (ProcAdd). The signature is "char* ProcAdd(char*)".
Now I do get the string correctly in the executable, but once I do "FreeLibrary", it's gone... (obviously because I just did a return "hello").
The thing is, that I have another dll (.NET, C#) where the signature is "[return: MarshalAs LPSTR]string ProcAdd([MarshalAs LPSTR] string)". Now this function ALSO returns a string, but when I do "FreeLibrary", the string is still accessible within my executable?!
How does that come, and how could I mimic the same behaviour? (and yes, I know I can store it in another variable, but I would like to understand what is happening and how I can reproduce this .NET behaviour).
Thanks a lot!
As requested the code:
C++ exe:
int main( void )
{
HINSTANCE hinstLib;
MYPROC ProcAdd;
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;
void * val = NULL;
// Get a handle to the DLL module.
// hinstLib = LoadLibrary(TEXT("C:\\Users\\steven\\temp\\myMyMy.orig.dll"));
hinstLib = LoadLibrary(TEXT("C:\\Users\\steven\\temp\\myMyMy.proxy.dll"));
// If the handle is valid, try to get the function address.
if (hinstLib != NULL)
{
ProcAdd = (MYPROC) GetProcAddress(hinstLib, "ProcAdd");
// If the function address is valid, call the function.
if (NULL != ProcAdd)
{
fRunTimeLinkSuccess = TRUE;
val = (ProcAdd) ("0987654321");
}
// Free the DLL module.
fFreeResult = FreeLibrary(hinstLib);
}
// If unable to call the DLL function, use an alternative.
if (! fRunTimeLinkSuccess)
printf("Message printed from executable\n");
return 0;
}
C++ dll:
#include <Windows.h>
#include <iostream>
#include <fstream>
static const char tmp[] = "hello";
extern "C" const char * __stdcall ProcAdd(const char * param1) {
FILE * fp = fopen("C:\\tmp\\ProcAdd.txt", "a");
if ( fp ) {
fprintf(fp, "param1: '%s'\r\n", param1);
fclose(fp);
}
// return strdup("hello");
// return "hello";
return tmp;
}
C# dll:
[return: MarshalAs(UnmanagedType.LPStr)]
public static string ProcAdd([MarshalAs(UnmanagedType.LPStr)] string param1)
{
string str;
try
{
str = new WebClient().DownloadString("http://www.salvania.be/test.php?param1=" + param1);
}
catch (Exception exception1)
{
str = "Error-DLL";
}
return str;
}
Working return:
// http://stackoverflow.com/questions/14406818/heapcreate-and-heapalloc-confuse
HANDLE winHandle = HeapCreate( 0, sizeof(tmp), sizeof(tmp) );
char* s = (char*)HeapAlloc( winHandle, 0, sizeof(tmp) + 1 );
strcpy((char*)s, tmp);
s[sizeof(tmp)] = 0;