与GetNamedPipeClientComputerName的C#互操作

我正在尝试使用互操作调用来获取C#中命名管道客户端的进程ID和计算机名称:

[DllImport("kernel32.dll",SetLastError = true)]
internal static extern bool GetNamedPipeclientProcessId(IntPtr Pipe,out uint ClientProcessId);

private static uint getclientProcessID(NamedPipeServerStream pipeServer)
{
    uint processId;
    IntPtr pipeHandle = pipeServer.SafePipeHandle.DangerousGetHandle();
    if (GetNamedPipeclientProcessId(pipeHandle,out processId))
    {
        return processId;
    }
    return 0;
}

[DllImport("kernel32.dll",SetLastError = true)]
internal static extern bool GetNamedPipeclientComputerName(IntPtr Pipe,out string ClientComputerName,uint ClientComputerNameLength);

private static string getclientComputerName(NamedPipeServerStream pipeServer)
{
    string computerName;
    uint buffer = 32768;
    IntPtr pipeHandle = pipeServer.SafePipeHandle.DangerousGetHandle();
    if (GetNamedPipeclientComputerName(pipeHandle,out computerName,buffer))
    {
        return computerName;
    }
    return null;
}

GetNamedPipeclientProcessId调用正在工作,但是GetNamedPipeclientComputerName返回false。是什么导致那个失败?

a12473740 回答:与GetNamedPipeClientComputerName的C#互操作

您应该使用StringBuilder而不是String

[DllImport("kernel32.dll",SetLastError = true)]
internal static extern bool GetNamedPipeClientComputerName(IntPtr Pipe,StringBuilder ClientComputerName,uint ClientComputerNameLength);

然后,您需要这样称呼它:

var computerName = new StringBuilder(buffer);
...
if (GetNamedPipeClientComputerName(pipeHandle,computerName,buffer))
{
    return computerName.ToString();
}
else throw new Win32Exception();
本文链接:https://www.f2er.com/3159622.html

大家都在问