I never got an answer to the question in the title, so I still don't know SecureString is marshalled to unmanaged code.
I did, however, get my code working by using the suggestions in some of the other answers. I have provided the code below.
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);
}
}
...
}
Instead of Marshal.SecureStringToBSTR I used Marshal.SecureStringToGlobalAllocUnicode because thats's what the unmanaged function expects, but other than that it works a treat.
Hopefully someone else finds this useful.
Kep.