将托管 String 中的内容复制到非托管内存,并在复制时转换为 ANSI 格式。
命名空间: System.Runtime.InteropServices
程序集: mscorlib(在 mscorlib.dll 中)
异常 | 条件 |
---|---|
OutOfMemoryException | 没有足够的可用内存。 |
ArgumentOutOfRangeException | s 参数超过了操作系统所允许的最大长度。 |
StringToHGlobalAnsi 对于自定义封送处理或者在混合托管和非托管代码时很有用。由于此方法分配字符串所需的非托管内存,因此应始终通过调用FreeHGlobal 来释放内存。StringToHGlobalAnsi 提供Marshal::PtrToStringAnsi 的相反功能。
using namespace System; using namespace System::Runtime::InteropServices; int main() { // Create a managed string. String^ managedString = "Hello unmanaged world (from the managed world)."; // Marshal the managed string to unmanaged memory. char* stringPointer = (char*) Marshal::StringToHGlobalAnsi(managedString ).ToPointer(); // Always free the unmanaged string. Marshal::FreeHGlobal(IntPtr(stringPointer)); return 0; }