gpt4 book ai didi

c# - 如何将 IntPtr/Int 转换为 Socket?

转载 作者:太空狗 更新时间:2023-10-29 23:04:45 24 4
gpt4 key购买 nike

我想将 message.WParam 转换为 Socket。

    protected override void WndProc(ref Message m)
{
if (m.Msg == Values.MESSAGE_ASYNC)
{

switch (m.LParam.ToInt32())
{
case Values.FD_READ:
WS2.Receive(m.WParam);
case Values.FD_WRITE: break;
default: break;
}

}
else
{
base.WndProc(ref m);
}
}

public class WS2
{
public static void Receive(IntPtr sock)
{
Socket socket = sock;
}
}

如何将 IntrPtr(sock) 转换为 Socket 以便调用 Receive()?

最佳答案

你不能这样做,因为 Socket 类创建并管理它自己的私有(private)套接字句柄。理论上,您可以使用一些邪恶的反射将您的套接字句柄插入套接字的私有(private)字段,但那完全是一种黑客攻击,我不会这样做。

给定一个有效的套接字句柄,您可以通过 P/Invoke 调用 Win32 recv 函数来接收数据,如下所示:

[DllImport("ws2_32.dll")]
extern static int recv([In] IntPtr socketHandle, [In] IntPtr buffer,
[In] int count, [In] SocketFlags socketFlags);

/// <summary>
/// Receives data from a socket.
/// </summary>
/// <param name="socketHandle">The socket handle.</param>
/// <param name="buffer">The buffer to receive.</param>
/// <param name="offset">The offset within the buffer.</param>
/// <param name="size">The number of bytes to receive.</param>
/// <param name="socketFlags">The socket flags.</param>
/// <exception cref="ArgumentException">If <paramref name="socketHandle"/>
/// is zero.</exception>
/// <exception cref="ArgumentNullException">If <paramref name="buffer"/>
/// is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">If the
/// <paramref name="offset"/> and <paramref name="size"/> specify a range
/// outside the given buffer.</exception>
public static int Receive(IntPtr socketHandle, byte[] buffer, int offset,
int size, SocketFlags socketFlags)
{
if (socketHandle == IntPtr.Zero)
throw new ArgumentException("socket");
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0 || offset >= buffer.Length)
throw new ArgumentOutOfRangeException("offset");
if (size < 0 || offset + size > buffer.Length)
throw new ArgumentOutOfRangeException("size");

unsafe
{
fixed (byte* pData = buffer)
{
return Recv(socketHandle, new IntPtr(pData + offset),
size, socketFlags);
}
}
}

关于c# - 如何将 IntPtr/Int 转换为 Socket?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/765364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com