C # Взаимодействие с GetNamedPipeClientComputerName - PullRequest
1 голос
/ 05 ноября 2019

Я пытаюсь использовать вызов взаимодействия, чтобы получить идентификатор процесса и имя компьютера клиента именованного канала в C #:

[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 возвращаетсяложный. Что может привести к тому, что этот сбой?

1 Ответ

2 голосов
/ 05 ноября 2019

Вы должны использовать 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();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...