I am currently working on a C++ dll, which returns a string to the caller. In order to keep the dll independent from the rest of the build process, as well as C++'s lack of a standard ABI, I am forced to wrap the strings with C char pointers.
As far as I recall, there are two possibilities of returning strings in plain C fashion:
//Method 1
bool Foo1(wchar_t* s1, int len)
{
//Needs space for 6 chars + null terminator
if (len < 7)
return false;
wcscpy(s1, L"Hello1");
return true;
}
//Method 2
wchar_t* Foo2()
{
wchar_t* s2 = new wchar_t[10];
wcscpy(s2, L"Hello2");
return s2;
}
//Caller
int _tmain(int argc, _TCHAR* argv[])
{
wchar_t s1[10];
bool res = Foo1(s1, sizeof(s1) / sizeof(WCHAR));
wchar_t* s2 = Foo2();
delete s2;
return 0;
}
Is there any guideline present which would favor one of these two solutions? I've seen Method 1 being used predominantly in the Windows API, probably due to historic reasons. However, I also don't see any negative impact in using the second method, which eliminates the need for the caller to allocate memory in beforehand. The only drawback would be that the responsibility of freeing the assigned memory now lies in the hands of the caller. Thanks for your suggestions.
delete. blogs.msdn.com/b/oldnewthing/archive/2006/09/15/755966.aspxwchar_t s1[10]; bool res = Foo1(s1, sizeof(s1) / sizeof(WCHAR));is dubious. Since the type ofs1iswchar_t, you should use that rather thanWCHARin the secondsizeof. Alternatively, and generally better, you can use:wchar_t s1[10]; bool res = Foo1(s1, sizeof(s1) / sizeof(s1[0]));, dividing the size of the array by the size of a single element in the array. The advantage of this is it continues to be correct regardless of the type ofs1.