MonoTouch: send / receive NSData though GameKit

I am trying to implement matchmaking in my MonoTouch game. I have successfully implemented a system for connecting players through GameKit, but I am stuck on sending and receiving data.

How do I convert this objective-c code to C #? The type of data I would like to send is a class Vector2with float Xand components Y.

NSError *error;
PositionPacket msg;
msg.messageKind = PositionMessage;
msg.x = currentPosition.x;
msg.y = currentPosition.y;
NSData *packet = [NSData dataWithBytes:&msg length:sizeof(PositionPacket)];
[match sendDataToAllPlayers: packet withDataMode: GKMatchSendDataUnreliable error:&error];

if (error != nil)
{
    // handle the error
}

Any help would be greatly appreciated!

+3
source share
2 answers

, OpenTK.Vector2 [Serializable], Stream (, a MemoryStream), NSData, . NSData.FromStream. , .

Stream, (, StreamWriter). () ( ).

MemoryStream ms = new MemoryStream ();
using (StreamWriter sw = new StreamWriter (ms)) {
    sw.Write (v2.X);
    sw.Write (v2.Y);
}
ms.Position = 0;
var data = NSData.FromStream (ms);

( ) unsafe code NSData.FromBytes, IntPtr () . , .

Vector2 , monotouch.dll, . PointF. NSData.FromObject. API NSObject, , NSValue monotouch.dll, . RectangleF, PointF,...

var v2 = new OpenTK.Vector2 ();
var pt = new System.Drawing.PointF (v2.X, v2.Y);
var data = NSData.FromObject (pt);
+1

, , . , , .

unsafe
{
    NSError error = new NSError((NSString)"Test", 0);

    System.IntPtr pointer = Marshal.AllocHGlobal(sizeof(PointF));

    PointF packedData = new PointF(position.X, position.Y);

    Marshal.StructureToPtr(packedData, pointer, false);

    NSData packet = NSData.FromBytes(pointer, (uint)sizeof(PointF));

    currentMatch.SendDataToAllPlayers(packet, GKMatchSendDataMode.Unreliable, error.ClassHandle);

    Marshal.FreeHGlobal(pointer);
}

, , NSError, . .

PointF packedData = (PointF)Marshal.PtrToStructure(data.Bytes, typeof(PointF));

var recievedData = new Vector2(packedData.X, packedData.Y);
0

All Articles