C# 从C调用WSASend#
这是我的代码,但我没有成功:C# 从C调用WSASend#,c#,marshalling,winsock,C#,Marshalling,Winsock,这是我的代码,但我没有成功: Unmanaged.WsaBuf buffer = Unmanaged.WsaBuf.Create("Blah Blah"); IntPtr bufferPointer = Marshal.AllocHGlobal(Marshal.SizeOf(buffer)); Marshal.StructureToPtr(buffer, bufferPointer, true); IntPtr o; SocketError error = Unmanaged.WSA
Unmanaged.WsaBuf buffer =
Unmanaged.WsaBuf.Create("Blah Blah");
IntPtr bufferPointer = Marshal.AllocHGlobal(Marshal.SizeOf(buffer));
Marshal.StructureToPtr(buffer, bufferPointer, true);
IntPtr o;
SocketError error = Unmanaged.WSA_Send(
socket,
bufferPointer,
1,
out o,
SocketFlags.None,
IntPtr.Zero,
IntPtr.Zero);
下面是方法声明:
[DllImport("Ws2_32.dll", SetLastError = true, EntryPoint = "WSASend")]
public static extern SocketError WSA_Send(IntPtr socket, IntPtr buffer, int len, out IntPtr numberOfBytesSent, SocketFlags flags, IntPtr overlapped, IntPtr completionRoutine);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WsaBuf
{
public ulong Len;
public IntPtr Buf;
public static WsaBuf Create(string str)
{
byte[] connectBuf = Encoding.ASCII.GetBytes(str);
GCHandle pinnedArray = GCHandle.Alloc(connectBuf, GCHandleType.Pinned);
return new WsaBuf { Buf = pinnedArray.AddrOfPinnedObject(), Len = (ulong)connectBuf.Length };
}
public void Free()
{
if (!Buf.Equals(IntPtr.Zero))
{
GCHandle.FromIntPtr(Buf).Free();
}
}
}
这是我的WSABUF宣言:
[DllImport("Ws2_32.dll", SetLastError = true, EntryPoint = "WSASend")]
public static extern SocketError WSA_Send(IntPtr socket, IntPtr buffer, int len, out IntPtr numberOfBytesSent, SocketFlags flags, IntPtr overlapped, IntPtr completionRoutine);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WsaBuf
{
public ulong Len;
public IntPtr Buf;
public static WsaBuf Create(string str)
{
byte[] connectBuf = Encoding.ASCII.GetBytes(str);
GCHandle pinnedArray = GCHandle.Alloc(connectBuf, GCHandleType.Pinned);
return new WsaBuf { Buf = pinnedArray.AddrOfPinnedObject(), Len = (ulong)connectBuf.Length };
}
public void Free()
{
if (!Buf.Equals(IntPtr.Zero))
{
GCHandle.FromIntPtr(Buf).Free();
}
}
}
我在另一边什么也没收到。有什么想法吗?
u_long
是unsigned long
,它映射到uint
,因为它在Microsoft Visual C编译器上是一个4字节的量Len
应该是uint
。可能,WSASend
只查看了前4个字节,发现它们是0
,这是一个零长度的缓冲区
顺便说一句,您误用了
GCHandle.FromIntPtr
。看看这些文档,看看它到底有什么作用。这个问题无关紧要,所以我不会详细说明。当.NET公开TcpClient,甚至是Socket
类时,为什么要使用WinSock?@johnsaunds这是一个挂钩的情况,但MSDN很有用,还需要解决其他问题,但这似乎是解决发送问题的方法。