Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

In a Dll project (VC++) , I defined a function that get wchar_t* and return wchar_t* in a parameter.
My Question is this: Is it correct to create the pointer(new wchar_t*) with specified size then return it as parameter refernce ?
like "sret" in my code:
extern "C"
{

	__declspec(dllexport) int  Function(wchar_t*  s, wchar_t*  sret,  int len)
	{
		int sLen = wcslen(s);
		sret = new wchar_t(sLen+4);
		wcscpy_s(sret, sLen, s);
		wcscat_s(sret, 4, L"_456");
		len = wcslen(sret);
		return 1;
	}
}


I want to use this dll in other windows projects . They's memory doesn't occur with problems?

What I have tried:

new the wchar_t* into a dll function then return it
Posted
Updated 21-Jan-18 4:13am

This will not work because sret is a local pointer, so the calling application will still have it pointing somewhere else. You need the address of the pointer, something like:
C++
__declspec(dllexport) int  Function(wchar_t*  s, wchar_t**  sret,  int len)
{
    int sLen = wcslen(s);
    *sret = new wchar_t(sLen+4); // should be sLen + 5
    wcscpy_s(*sret, sLen, s);
    wcscat_s(*sret, 4, L"_456");
    len = wcslen(*sret); // what is this line for?

    return 1; // what is this line for?
}

However, a much better way would be to just return the pointer, something like:
C++
__declspec(dllexport) wchar_t* Function(wchar_t*  s)
{
    int sLen = wcslen(s);
    wchar_t* sret = new wchar_t[sLen + 5];
    wcscpy_s(sret, sLen, s);
    wcscat_s(sret, 4, L"_456");

    return sret;
}

Is there a specific reason that you think this needs to be in a DLL?
 
Share this answer
 
Comments
CPallini 21-Jan-18 10:08am    
5.
In addition to Richard solution, have a look at c++ - Is it bad practice to allocate memory in a DLL and give a pointer to it to a client app? - Stack Overflow[^].
Unfortunately mismatches between allocator and deallocator do happen and are not pleasant.
 
Share this answer
 
Comments
Richard MacCutchan 21-Jan-18 12:07pm    
Ha, ha. That told me :(

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900