Marshal.SecureStringToBSTR

Marshal.StringToBSTR 方法

命名空间:System.Runtime.InteropServices
程序集:mscorlib(在 mscorlib.dll 中)

// 使用一个IntPtr类型值来存储加密字符串的起始点 
IntPtr p = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(this.txtPwd.SecurePassword);
// 使用.NET内部算法把IntPtr指向处的字符集合转换成字符串 
string password = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(p); 

StringToBSTR 对于自定义封送处理或者在混合托管和非托管代码时很有用。由于该方法分配字符串所需的非托管内存,因此在完成操作时,应始终通过调用 Marshal.FreeBSTR 释放 BSTR。此方法提供Marshal.PtrToStringBSTR 的相反功能。

此方法使用 SecurityAction.LinkDemand 防止不可信代码对它进行调用;只有直接调用方才需要具有 SecurityPermissionAttribute.UnmanagedCode 权限。如果您的代码可从部分受信任的代码调用,则未经验证不要将用户输入传递给 Marshal 类方法。有关使用 LinkDemand 成员的重要限制,请参见 Demand 和 LinkDemand

勤劳一日,便得一夜安眠;勤劳一生,便得幸福长眠。
原文地址:https://www.cnblogs.com/zhaomengmeng/p/4562899.html