-2

I have a function that sets one of the parameters to outgoing. I need to use it with std::vector.

Here is the function that returns the filename into *sFilename that is declared as WCHAR **:

BOOL GetFilenameFromPathAndFilename(WCHAR *sFilenameAndPath, WCHAR **sFilename)
{
WCHAR *pDest;

// Count backwards to find the first backslash and take the right # of chars as the filename
pDest =wcsrchr(sFilenameAndPath,'\\');

if (pDest)
    {
    pDest++;
    DWORD dwLen = (DWORD) _tcslen(pDest) + 1;
    *sFilename = (WCHAR*)calloc(dwLen, sizeof(TCHAR));
    StringCchCopy(*sFilename,dwLen, pDest);
    }

return (pDest != 0);
}

How do I use this function with std::vector? Using a std::vector, the call does not work:

std::vector<WCHAR> sFQDN(512);
//GetFQDomainNameEx(&sFQDN.data());  <-does not work

WCHAR *sFilenameIncoming = NULL;
GetFQDomainNameEx(&sFilenameIncoming);  <-this works
JeffR
  • 765
  • 2
  • 8
  • 23

2 Answers2

2

Windows functions that accept a double pointer allocate dynamic memory themselves. Therefore, you cannot use them with preallocated memory. You must pass an empty pointer, the function will initialize it, and then you must free it according to the documentation.

Passing a vector, empty or not, will not work because the majority of Windows functions do not work with STL.

Now, since this seems to be your own function and not an internal one, you can modify it to accept a vector:

BOOL GetFilenameFromPathAndFilename(WCHAR *sFilenameAndPath, 
std::vector<WCHAR>& sFileName)  {
 ....

sFilename.resize(dwLen);
StringCchCopy(sFilename.data(),dwLen, pDest);
Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
2

With this function, you must pass a pointer variable, like this for example:

WCHAR *sFilenameIncoming;
GetFQDomainNameEx(&sFilenameIncoming);  <-this works

You can then copy the data pointed by sFilenameIncoming into a container, and free the allocation.


//GetFQDomainNameEx(&sFQDN.data()); <-does not work

This does not work, because sFQDN.data() is an rvalue, so you cannot take its address.

eerorika
  • 232,697
  • 12
  • 197
  • 326