Reference as an out parameter from DLL

I have written a DLL in C++ and my C++ application is consuming it. Function "Convert" of the dll returns unsigned long and takes a "String" object reference as parameter. The function is supposed to assign value to the String obj and the caller will get changed value because String is passed by reference.

This works as expected. I am getting back String reference filled. But when I unload the dll the String object becomes void. I am not able to understand this as the out parameter is defined in caller and hence memory allocated to it should not become void on DLL unload.

String is defined as:
***
typedef wchar_t StringChar;
typedef std::basic_string<StringChar> String;
***

Pleas see my code below:

***
Header
======

#ifdef EXPORTING_DLL
extern "C" unsigned long __declspec(dllexport) Convert(String & res) ;
#else
extern "C" unsigned long __declspec(dllimport) Convert(String & res) ;
#endif
***

***
DLL Implementation
==================

unsigned long Convert(String & res)
{
String tmp;

tmp = myfunc(); // myfunc returns String object
res = tmp; // Done this for easy reading and avoid confusion

// To narrow down I assigned a value to res here. Meaning I was not dependent on the value returned by myfunc()
// but still the problem occurs proving that issue is not because of the return value from myfunc()

return <unsigned long value obtained from completely unrelated processing>;
}
***

***
Caller code
============

foo()
{
typedef unsigned long (*DLLPROC) (String & result);
HINSTANCE hinstDLL;
DLLPROC ConvertFunc;
BOOL fFreeDLL;
String r1;

hinstDLL = LoadLibrary("C:\\Convert.dll");

if (hinstDLL != NULL)
{
ConvertFunc = (DLLPROC) GetProcAddress(hinstDLL, "Convert");
if (ConvertFunc != NULL)
{
unsigned long ijk;
ijk = (ConvertFunc)(r1);
i = r1.length(); // Done just for sanity to chec kwhether we are correctly getting r1.
// We get r1 correctly here
}
else
{
DWORD dw = GetLastError();
cout << "Error in loading the DLL: " << dw;
}

// Till this point r1 has valid value

fFreeDLL = FreeLibrary(hinstDLL);

// After FreeLibrary r1 becomes bad pointer / void

cout << "Result: " << r1.c_str() << endl;
}
else
{
DWORD dw = GetLastError();
cout << "Error in loading the DLL: " << dw;
}
}
***

Any suggestions are appreciated.

Thanks,
Ganesh
Topic archived. No new replies allowed.