StringToBSTR Method
Collapse the table of content
Expand the table of content

Marshal.StringToBSTR Method

Allocates a BSTR and copies the contents of a managed String into it.

Namespace:  System.Runtime.InteropServices
Assembly:  mscorlib (in mscorlib.dll)

[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static IntPtr StringToBSTR(
	string s


Type: System.String

The managed string to be copied.

Return Value

Type: System.IntPtr
An unmanaged pointer to the BSTR, or 0 if a null string was supplied.


There is insufficient memory available.


The length for s is out of range.

StringToBSTR is useful for custom marshaling or when mixing managed and unmanaged code. Since this method allocates the unmanaged memory required for a string, always free the BSTR when finished by calling Marshal.FreeBSTR. This method provides the opposite functionality of Marshal.PtrToStringBSTR.


This method uses SecurityAction.LinkDemand to prevent it from being called from untrusted code; only the immediate caller is required to have SecurityPermissionAttribute.UnmanagedCode permission. If your code can be called from partially trusted code, do not pass user input to Marshal class methods without validation. For important limitations on using the LinkDemand member, see Demand vs. LinkDemand.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0

Community Additions

© 2015 Microsoft