c++ 添加新用户时出现错误“无法将“const wchar_t”类型的值分配给“LPWSTR”类型的实体”

ktecyv1j  于 2023-01-06  发布在  其他
关注(0)|答案(2)|浏览(273)

当我尝试在C++中创建用户帐户时,出现错误
类型为“const wchar_t”的值不能分配给类型为“LPWSTR”的实体
usri1_nameusri1_password上出现两次等号错误。使用Visual Studio 2019编译。有什么想法吗?

#ifndef UNICODE
#define UNICODE
#endif
#pragma comment(lib, "netapi32.lib") //heard this is dynamic linking ?

#include <windows.h>
#include <lm.h>

int main()
{
    USER_INFO_1 ui;
    DWORD dwLevel = 1;
    DWORD dwError = 0;
    //NET_API_STATUS nStatus;

    ui.usri1_name = L"istech";
    ui.usri1_password = L"p@ssword";
    ui.usri1_priv = USER_PRIV_USER;
    ui.usri1_home_dir = NULL;
    ui.usri1_comment = NULL;
    ui.usri1_flags = UF_PASSWD_CANT_CHANGE;
    ui.usri1_script_path = NULL;

    NetUserAdd(NULL, dwLevel, (LPBYTE)&ui, &dwError);

}
eqqqjvef

eqqqjvef1#

usri_nameusri_password字段是指向 * nonconst * Unicode缓冲区的指针,但您试图将字符串常量赋给它们,它们是 const 数据。
因此,您可以:

  • const_cast去掉了常量的值(要特别小心!):
ui.usri1_name = const_cast<wchar_t*>(L"istech");
ui.usri1_password = const_cast<wchar_t*>(L"p@ssword");
  • 将文字内容复制到本地wchar_t[]数组中:
wchar_t name[] = L"istech";
wchar_t pass[] = L"p@ssword";

ui.usri1_name = name;
ui.usri1_password = pass;
r1zk6ea1

r1zk6ea12#

对于任何需要解决方案的人,下面是对我有效的方法:

USER_INFO_1 user_info;
    ZeroMemory(&user_info, sizeof(user_info));
    wchar_t name[] = L"istech"; 
    wchar_t pass[] = L"password";
    user_info.usri1_name = name;
    user_info.usri1_password = pass;
    user_info.usri1_priv = USER_PRIV_USER;
    user_info.usri1_flags = UF_SCRIPT | UF_DONT_EXPIRE_PASSWD | UF_PASSWD_CANT_CHANGE;

    DWORD dwLevel = 1;
    DWORD dwError = 0;
    NET_API_STATUS nStatus = NetUserAdd(NULL, dwLevel, (LPBYTE)&user_info, &dwError);

相关问题