如何设置通过引用函数提供的 LPWSTR 指针?

How to set a LPWSTR pointer which has been provided by reference to a function?

我正在替换一个旧的 DLL,它有一个函数,通过引用传递一个 LPWSTR。 这些函数应该创建一个新的 wchar 缓冲区和 return 新创建的 LPWSTR 指针。我找到了解决方案,但我认为它可以更好地解决!?

在主程序中,DLL 函数是这样调用的:

LPWSTR data = null;
funcA(&data);

该函数应该创建一个新的 wchar 缓冲区和 return 地址。

所以这就是我所做的(有效):

void funcA(LPWSTR szData)
{
  LPWSTR newData = L"DEMODATA";
  LPWSTR newBuffer = new TCHAR[9];
  wmemcpy(newBuffer, newData, 9);

  memcpy(szData, (LPWSTR)&newBuffer , sizeof(LPWSTR));  
}

是否可以将最后一行写得更易读? 我尝试分配新指针,但这不起作用:

szData = (LPWSTR)&newBuffer; // not working!

The function shoud creat a new wchar buffer and return the address.

然后就这样做:

LPWSTR funcA() {
  LPWSTR newData = L"DEMODATA";
  LPWSTR newBuffer = new TCHAR[9];
  wmemcpy(newBuffer, newData, 9);

  return newBuffer;
}

LPWSTR data = funcA();

也就是说,考虑使用 unique_ptr 来存储拥有的指针。这会起作用,但这是不好的做法。更好的是,使用 std::string 处理数据,只在必要时转换为 WinAPI 指针。

memcpy(szData, (LPWSTR)&newBuffer , sizeof(LPWSTR));  

相当于

*(LPWSTR*)szData = newBuffer; //this copies into the address pointed to by szData

不要

szData = (LPWSTR)&newBuffer; // this copies into szData

passing an LPWSTR by reference

但你不这样做...

void funcA(wchar_t* data); // LPWSTR resolved to what it actually is
                           // using correct pointers illustrates better
                           // than Microsoft's (valueless?) pointer typedefs...

您传递的原始指针被复制到函数参数中,然后对该副本进行赋值。

您实际上需要能够分配给外部地址,因此您需要执行您已经描述的操作:

void funcA(wchar_t*& data); // reference to pointer
//                 ^ (!)
{
    wchar_t const* newData = L"DEMODATA"; // literals are const!
    data = new wchar_t[9]; // you can assign directly (especially: no need for memcpy)
    wmemcpy(data, newData, 9);
}

只是为了进一步说明,可能有助于更好地理解:指向指针的 C 样式指针:

void funcA(wchar_t** data); // pointer to pointer
//                 ^
{
    wchar_t* newData = new wchar_t[9];
    wmemcpy(newData, L"DEMODATA", 9);
    *data = newData;
//  ^ (!)
};

此变体的用法:

wchar_t* text;
funcA(&text);
//    ^ (!)