根据 Reflector 的说法,.Net Framework 在内部执行此操作的方式是将StringBuilder
实例传递给 char** 参数,而其他(数字)指针通常以IntPtr
. 一个很好的例子是FormatMessage
,它具有以下签名:
DWORD WINAPI FormatMessage(
_In_ DWORD dwFlags,
_In_opt_ LPCVOID lpSource,
_In_ DWORD dwMessageId,
_In_ DWORD dwLanguageId,
_Out_ LPTSTR lpBuffer,
_In_ DWORD nSize,
_In_opt_ va_list *Arguments
);
定义Microsoft.Win32.SafeNativeMethods
为
[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern int FormatMessage(int dwFlags, HandleRef lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr arguments);
System.ComponentModel.Win32Exception
,它调用这个方法,确实
int error = 0; //Error code, for example
StringBuilder lpBuffer = new StringBuilder(0x100);
SafeNativeMethods.FormatMessage(0x3200, NativeMethods.NullHandleRef, error, 0, lpBuffer, lpBuffer.Capacity + 1, IntPtr.Zero)
如果要提取size参数,可以定义一个不安全的方法,实际使用int*
size参数的类型。