我从未得到标题中问题的答案,所以我仍然不知道 SecureString 已编组为非托管代码。
然而,我确实通过使用其他一些答案中的建议来使我的代码正常工作。我提供了下面的代码。
internal static class NativeService
{
...
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ChangeServiceConfig(IntPtr hService, uint nServiceType, uint nStartType, uint nErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, [In] char[] lpDependencies, string lpServiceStartName, IntPtr lpPassword, string lpDisplayName);
...
public const uint SERVICE_NO_CHANGE = 0xffffffff;
}
internal class ClassThatConfiguresService
{
...
public void ConfigureStartupAccount(IntPtr service, string userName, SecureString password)
{
passwordPointer = Marshal.SecureStringToGlobalAllocUnicode(password);
try
{
if(!NativeService.ChangeServiceConfig(service, NativeService.SERVICE_NO_CHANGE, NativeService.SERVICE_NO_CHANGE, NativeService.SERVICE_NO_CHANGE, null, null, IntPtr.Zero, null, userName, passwordPointer, null))
throw new Win32Exception(Marshal.GetLastWin32Error());
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(passwordPointer);
}
}
...
}
我没有使用 Marshal.SecureStringToBSTR,而是使用了 Marshal.SecureStringToGlobalAllocUnicode,因为这是非托管函数所期望的,但除此之外,它还是一种享受。
希望其他人发现这很有用。
凯普。