I've made a couple of methods to receive and send a class in C#. Problem is that to use the sending one, I have to supply it with an int pointer as a parameter, representing a pointer to the object I'm sending. To do this, I'm trying to use the StructureToPtr method, but it's giving me a hard time. :( When I run the code, I get an error message saying "The specified structure must be blittable or have layout information". What does that mean? How do I resolve this issue? I've already looked in MSDN, the documentation is useless.
Here's the code:
public unsafe Program()
{
Socket = new NetFXSocket(false, "127.0.0.1");
StateObject ThisState = new StateObject(0, Socket.Listener, 1024);
if (Socket.Connected == true)
Console.WriteLine("Successfully connected to server!");
User NewUser = new User(ThisState);
IntPtr Ptr = Marshal.AllocCoTaskMem(1024);
Marshal.StructureToPtr(NewUser, Ptr, false);
NewUser.Name = "Mats";
NewUser.Password = "Prins";
NewUser.SendObject(Ptr);
}
Oh and here's the code for the User class:
using System;
using System.Collections.Generic;
using System.Text;
using NetFX;
using System.Net.Sockets;
using System.Runtime.InteropServices;
namespace NimdalinNetwork
{
public class User : NetworkObject
{
public StateObject ThisState;
public string Name;
public string Password;
public User(StateObject ParamState)
{
ThisState = ParamState;
}
public override unsafe void SendObject(IntPtr Ptr)
{
object Obj = new object();
Marshal.PtrToStructure(Ptr, Obj);
byte[] buf = (byte[])Obj;
ThisState.StateSocket.Send(buf);
}
public override void ReceiveObject()
{
byte[] buf = new byte[1024];
ThisState.StateSocket.BeginReceive(ThisState.buf, 0, 1024, SocketFlags.None,
new AsyncCallback(HandleReceive), ThisState);
}
private void HandleReceive(IAsyncResult ar)
{
StateObject State = (StateObject)ar.AsyncState;
Socket Client = State.StateSocket;
int Read = Client.EndReceive(ar);
if (Read > 0)
{
//Not all the data was read, so read more...
Client.BeginReceive(State.buf, 0, 1024, SocketFlags.None,
new AsyncCallback(HandleReceive), State);
}
else if (State.buf.Length > 1)
{
//Store the new user item in the RecvdObj object.
State.RecvdObj = (object)State.buf;
}
Client.Close();
}
}
}
Thanks in advance for any help!
Edit; This line is the one that gives me the error - "Marshal.StructureToPtr(NewUser, Ptr, false);"