[英]C# Pointer: error CS0254: The right hand side of a fixed statement assignment may not be a cast expression
I have a c++ server and now a trying to make ac# client. 我有一个c ++服务器,现在正在尝试制作ac#客户端。
In c++, to send a packet I make this: 在c ++中,要发送数据包,请执行以下操作:
PMessage *msg = (PMessage*)&buf[0];
msg->id = PID_LOGIN;
sendto(sServer, buf, sizeof(buf), 0, (SOCKADDR*)&from, fromlen);
in c# I trying this: 在C#中我尝试这样做:
unsafe
{
try
{
byte[] rawdata = new byte[Marshal.SizeOf(typeof(PMessage))];
fixed (PMessage* p = (PMessage*)&rawdata[0])
{
// p->id = 1001;
}
udpClient.Send(rawdata, rawdata.Length); ;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
The compiler show this error: 编译器显示此错误:
error CS0254: The right hand side of a fixed statement assignment may not be a cast expression. 错误CS0254:固定语句分配的右侧可能不是强制转换表达式。
c#: C#:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct PMessage
{
public fixed byte msg[256];
public int id;
public int size;
}
c++: C ++:
struct PMessage
{
char msg[256];
unsigned int id;
unsigned int size;
};
Try this: 尝试这个:
PMessage p = new PMessage();
// p.id = 1001;
byte[] rawdata = new byte[Marshal.SizeOf(typeof(PMessage))];
IntPtr mem = Marshal.AllocHGlobal(rawdata.Length);
try{
Marshal.StructureToPtr(p, mem, true);
Marshal.Copy(mem, rawdata, 0, rawdata.Length);
}finally{
Marshal.FreeHGlobal(mem);
}
udpClient.Send(rawdata, rawdata.Length);
Also don't mix unsafe ( fixed
) and unmanaged ( SizeOf
) environments. 也不要将不安全( fixed
)和非托管( SizeOf
)环境混合使用。
You can't do this, because the compiler loses track of which object needs to be pinned. 您无法执行此操作,因为编译器无法跟踪需要固定哪个对象。
fixed (PMessage* p = (PMessage*)&rawdata[0])
However this should work 但是,这应该工作
fixed (byte* pby = &rawdata[0]) {
PMessage* p = (PMessage*)pby;
Please note that your C++ code was probably violating strict aliasing, and both C++ and C# may not have correct alignment. 请注意,您的C ++代码可能违反了严格的别名,并且C ++和C#可能没有正确的对齐方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.