예제 #1
0
 void OnDestroy()
 {
     set_recurring_reply(gameObject.GetHashCode(), null);
     _recurring_callback_holder = null;
     set_recurring_data_push(gameObject.GetHashCode(), null);
     _recurring_data_push_holder = null;
 }
 public void ProtocolWithBlockProperties(bool required, bool instance)
 {
     using (var pb = new PropertyBlock()) {
         var            callbackCalled = false;
         SimpleCallback action         = () => {
             callbackCalled = true;
         };
         if (required)
         {
             if (instance)
             {
                 pb.MyRequiredProperty = action;
             }
             else
             {
                 PropertyBlock.MyRequiredStaticProperty = action;
             }
         }
         else
         {
             if (instance)
             {
                 pb.MyOptionalProperty = action;
             }
             else
             {
                 PropertyBlock.MyOptionalStaticProperty = action;
             }
         }
         ObjCBlockTester.CallProtocolWithBlockProperties(pb, required, instance);
         Assert.IsTrue(callbackCalled, "Callback");
     }
 }
예제 #3
0
 void OnApplicationQuit()
 {
     set_recurring_reply(gameObject.GetHashCode(), null);
     _recurring_callback_holder = null;
     set_recurring_data_push(gameObject.GetHashCode(), null);
     _recurring_data_push_holder = null;
 }
예제 #4
0
 public Notification(NotificationType t, string tex, bool s, SimpleCallback cb)
 {
     Type           = t;
     Text           = tex;
     ShowHideButton = s;
     Callback       = cb;
 }
예제 #5
0
    void Awake()
    {
        Debug.Log("testing callbacks on object:" + gameObject.GetHashCode());

        // during the course of this call into the plugin, it will call back the _onetime_callback() function.
        // because the plugin call/marshaling layer retains a reference to the SimpleCallback delegate, it
        // can not be freed or GC'd during the call
        // all of the following syntaxes work:
        // 1. reply_during_call(new SimpleCallback(this._onetime_callback));
        // 2. reply_during_call(this._onetime_callback);
        // 3. below, the most clear form
        reply_during_call(_onetime_callback);

        // to pass a delegate that is called after the call into the plugin completes, either later
        // or repeatedly later, you have to retain the delegate, which you can only do by holding
        // it in a wider-scope, in this case in a private member/ivar. the marshaling layer will
        // add a hold/addref/retain to the delegate during the call and release it on return, so
        // unless you are holding on to it the plugin would be left with an invalid pointer as
        // soon as GC runs. it's worth understanding that the delegate is effectively two "objects":
        // a managed object in C# which may move due to GC which is holding onto a fixed
        // (possibly unmanaged - that's runtime-dependent) function-pointer which is what the
        // plugin can refer to. GC may move the managed C# object around, but the function pointer
        // in the native-code plugin remains immobile.
        _recurring_callback_holder = new SimpleCallback(_recurring_callback);
        set_recurring_reply(gameObject.GetHashCode(), _recurring_callback_holder);

        // this is a one-time data-polling call to pull bytes from native/unmanaged code.
        // the difficulty with a poll API is that the plugin cannot allocate memory for the
        // caller easily unless both sides agree how it is going to be released. a polling
        // API can be useful if you have a native data structure or very long-lived buffer
        // associated with the specific object instance that Unity can depend on not moving
        // or disappearing. alternately you can force the caller to deallocate the memory
        // returned from the poll. as with any real-time system, though, you want to make
        // sure you are minimizing data copies (and conversions), so think through the
        // memory lifetimes carefully.
        IntPtr buffer = IntPtr.Zero, length = IntPtr.Zero;

        poll_data(gameObject.GetHashCode(), out buffer, out length);
        if (buffer != IntPtr.Zero && length != IntPtr.Zero)
        {
            int    len  = length.ToInt32();
            byte[] data = new byte[len];
            Marshal.Copy(buffer, data, 0, len);
            Debug.Log("polled " + len + " bytesinto C# as " + data);
        }

        // this recurring callback, like the SimpleCallback, must be held longer than the
        // duration of the call. this example is to demonstrate a common requirement: passing
        // data between a native/unmanaged plugin C#. in this case the native plugin pushes
        // raw bytes of data into a C# byte[], which is a nice way to control the lifetime
        // of the data on the plugin's side - by the time the callback returns the plugin
        // knows Unity/C# has no further access, they should have copied what they needed.
        // this form of "push" API's where the native side buffers data and pushes it to
        // Unity/C# and the C# side also buffers and uses and frees it on its own schedule
        // is a pretty safe design which can minimize the total number of data copies
        // and problems with memory leaks.
        _recurring_data_push_holder = new DataCallback(_recurring_data_push);
        set_recurring_data_push(gameObject.GetHashCode(), _recurring_data_push_holder);
    }
예제 #6
0
        public void DelegateMethodTest()
        {
            SimpleCallback callback = new SimpleCallback(SimpleCallbackImpl);

            method            = GetMethodForTest("SimpleCallbackImpl");
            messageCollection = rule.CheckMethod(method, new MinimalRunner());
            Assert.IsNull(messageCollection);
        }
        public void DelegateMethodTestWithMultipleDelegates()
        {
            SimpleCallback callback  = new SimpleCallback(SimpleCallbackImpl);
            SimpleCallback callback2 = new SimpleCallback(SimpleCallbackImpl2);

            AssertRuleDoesNotApply <AvoidUnusedParametersTest> ("SimpleCallbackImpl");
            AssertRuleDoesNotApply <AvoidUnusedParametersTest> ("SimpleCallbackImpl2");
        }
 public void Logout(SimpleCallback callback = null)
 {
     UserId       = null;
     UserName     = null;
     UserEmail    = null;
     UserLoggedIn = false;
     callback?.Invoke();
 }
예제 #9
0
        public void TC015_MultipleResponseCallback()
        {
            bool       errorThrown = false;
            List <int> expected    = new List <int>();
            List <int> response    = new List <int>();

            AutoResetEvent resetEvent = new AutoResetEvent(false);

            using (IReactor natsClient = ReactorFactory.GetReactor(typeof(Reactor)))
            {
                natsClient.OnError += new EventHandler <ReactorErrorEventArgs>(delegate(object sender, ReactorErrorEventArgs args)
                {
                    errorThrown = true;
                    resetEvent.Set();
                });

                natsClient.Start(natsEndpoint);

                SimpleCallback[] delegates = new SimpleCallback[] {
                    delegate() { response.Add(0); },
                    delegate() { response.Add(1); },
                    delegate() { response.Add(2); },
                    delegate() { response.Add(3); },
                    delegate() { response.Add(4); },
                    delegate() { response.Add(5); },
                    delegate() { response.Add(6); },
                    delegate() { response.Add(7); },
                    delegate() { response.Add(8); },
                    delegate() { response.Add(9); },
                    delegate() { response.Add(10); },
                    delegate() { response.Add(11); },
                    delegate() { response.Add(12); },
                    delegate() { response.Add(13); },
                    delegate() { response.Add(14); }
                };

                for (int i = 0; i < 15; i++)
                {
                    expected.Add(i);
                    natsClient.Publish("foo", delegates[i]);
                }

                natsClient.Publish("foo", delegate()
                {
                    resetEvent.Set();
                });

                resetEvent.WaitOne(5000);
                natsClient.Close();
            }
            Assert.IsFalse(errorThrown);

            for (int i = 0; i < 15; i++)
            {
                Assert.AreEqual(expected[i], response[i]);
            }
        }
예제 #10
0
  void Awake () {
    Debug.Log("testing callbacks on object:" + gameObject.GetHashCode());

    // during the course of this call into the plugin, it will call back the _onetime_callback() function.
    // because the plugin call/marshaling layer retains a reference to the SimpleCallback delegate, it
    // can not be freed or GC'd during the call
    // all of the following syntaxes work:
    // 1. reply_during_call(new SimpleCallback(this._onetime_callback));
    // 2. reply_during_call(this._onetime_callback);
    // 3. below, the most clear form
    reply_during_call(_onetime_callback);

    // to pass a delegate that is called after the call into the plugin completes, either later
    // or repeatedly later, you have to retain the delegate, which you can only do by holding
    // it in a wider-scope, in this case in a private member/ivar. the marshaling layer will
    // add a hold/addref/retain to the delegate during the call and release it on return, so
    // unless you are holding on to it the plugin would be left with an invalid pointer as
    // soon as GC runs. it's worth understanding that the delegate is effectively two "objects":
    // a managed object in C# which may move due to GC which is holding onto a fixed
    // (possibly unmanaged - that's runtime-dependent) function-pointer which is what the
    // plugin can refer to. GC may move the managed C# object around, but the function pointer
    // in the native-code plugin remains immobile.
    _recurring_callback_holder = new SimpleCallback(_recurring_callback);
    set_recurring_reply(gameObject.GetHashCode(), _recurring_callback_holder);

    // this is a one-time data-polling call to pull bytes from native/unmanaged code.
    // the difficulty with a poll API is that the plugin cannot allocate memory for the
    // caller easily unless both sides agree how it is going to be released. a polling
    // API can be useful if you have a native data structure or very long-lived buffer
    // associated with the specific object instance that Unity can depend on not moving
    // or disappearing. alternately you can force the caller to deallocate the memory
    // returned from the poll. as with any real-time system, though, you want to make
    // sure you are minimizing data copies (and conversions), so think through the
    // memory lifetimes carefully.
    IntPtr buffer=IntPtr.Zero, length=IntPtr.Zero;
    poll_data(gameObject.GetHashCode(), out buffer, out length);
    if (buffer != IntPtr.Zero && length != IntPtr.Zero) {
      int len = length.ToInt32();
      byte[] data = new byte[len];
      Marshal.Copy(buffer, data, 0, len);
      Debug.Log("polled " + len + " bytesinto C# as " + data);
    }

    // this recurring callback, like the SimpleCallback, must be held longer than the
    // duration of the call. this example is to demonstrate a common requirement: passing
    // data between a native/unmanaged plugin C#. in this case the native plugin pushes
    // raw bytes of data into a C# byte[], which is a nice way to control the lifetime
    // of the data on the plugin's side - by the time the callback returns the plugin
    // knows Unity/C# has no further access, they should have copied what they needed.
    // this form of "push" API's where the native side buffers data and pushes it to
    // Unity/C# and the C# side also buffers and uses and frees it on its own schedule
    // is a pretty safe design which can minimize the total number of data copies
    // and problems with memory leaks.
    _recurring_data_push_holder = new DataCallback(_recurring_data_push);
    set_recurring_data_push(gameObject.GetHashCode(), _recurring_data_push_holder);
  }
예제 #11
0
        /// <summary>
        /// Queues the server.
        /// </summary>
        /// <param name="callback">The callback.</param>
        private void QueueServer(SimpleCallback callback)
        {
            if (callback == null)
            {
                return;
            }

            this.pongs.Enqueue(callback);
            this.SendCommand(this.resource.PINGREQUEST);
        }
예제 #12
0
        public void Init()
        {
            var responder = new SpecificResponder <Simple>(new SimpleImpl());

            server = new SocketServer("localhost", 0, responder);
            server.Start();

            transceiver  = new SocketTransceiver("localhost", server.Port);
            simpleClient = SpecificRequestor.CreateClient <SimpleCallback>(transceiver);
        }
예제 #13
0
    IEnumerator StartsPerClassTask(SimpleCallback callThis)
    {
        Debug.Log("starting");
        yield return(new WaitForSeconds(2));

        Debug.Log("finishing");

        //this is quite specific
        callThis.PersonalCall();
    }
        public void CreateMoreComplexCallable()
        {
            EasyType typebuilder = new EasyType(module, "mytype");

            ArgumentReference arg1     = new ArgumentReference(typeof(int));
            ArgumentReference arg2     = new ArgumentReference(typeof(DateTime));
            ArgumentReference arg3     = new ArgumentReference(typeof(object));
            EasyCallable      callable = typebuilder.CreateCallable(
                new ReturnReferenceExpression(typeof(string)),
                arg1, arg2, arg3);

            FieldReference field1 = typebuilder.CreateField("field1", callable.TypeBuilder);

            SimpleCallback sc = new SimpleCallback();

            ArgumentReference arg         = new ArgumentReference(typeof(SimpleCallback));
            EasyConstructor   constructor = typebuilder.CreateConstructor(arg);

            constructor.CodeBuilder.InvokeBaseConstructor();

            constructor.CodeBuilder.AddStatement(new AssignStatement(field1,
                                                                     new NewInstanceExpression(callable,
                                                                                               arg.ToExpression(),
                                                                                               new MethodPointerExpression(arg, typeof(SimpleCallback).GetMethod("RunAs")))));

            constructor.CodeBuilder.AddStatement(new ReturnStatement());

            arg1 = new ArgumentReference(typeof(int));
            arg2 = new ArgumentReference(typeof(DateTime));
            arg3 = new ArgumentReference(typeof(object));

            ReturnReferenceExpression ret1 = new ReturnReferenceExpression(typeof(string));

            EasyMethod getField1 = typebuilder.CreateMethod("Exec", ret1, arg1, arg2, arg3);

            getField1.CodeBuilder.AddStatement(
                new ReturnStatement(
                    new ConvertExpression(typeof(String),
                                          new MethodInvocationExpression(field1,
                                                                         callable.Callmethod,
                                                                         new ReferencesToObjectArrayExpression(arg1, arg2, arg3)))));

            Type newType = typebuilder.BuildType();

            RunPEVerify();

            object instance = Activator.CreateInstance(newType, new object[] { sc });

            MethodInfo method = instance.GetType().GetMethod("Exec");
            object     result = method.Invoke(instance, new object[] { 1, DateTime.Now, "" });

            Assert.AreEqual("hello2", result);
        }
예제 #15
0
 public static void ShowIt(GameWindow window)
 {
     FormScreenMark form = new FormScreenMark();
     form.Window = window;
     form.btnUpdateScreen_Click(form, null);
     SimpleCallback sc = new SimpleCallback(form.L2Window_ScreenshotUpdate);
     form.Window.ProgressBindings.ScreenshotUpdate += sc;
     form.Window.ProgressBindings.RefreshScreenshot();
     form.updateWhoList();
     form.ShowDialog();
     window.ProgressBindings.ScreenshotUpdate -= sc;
 }
예제 #16
0
        }//OnLookAround

        public IEnumerator LookAround(SimpleCallback callback = null)
        {
            yield return(new WaitForSeconds(1f));

            DirSwitcherCmp.OnSwitchDirection();
            yield return(new WaitForSeconds(1f));

            DirSwitcherCmp.OnSwitchDirection();
            yield return(new WaitForSeconds(1f));

            callback?.Invoke();
        }//LookAround
예제 #17
0
        public static void ShowIt(GameWindow window)
        {
            FormScreenMark form = new FormScreenMark();

            form.Window = window;
            form.btnUpdateScreen_Click(form, null);
            SimpleCallback sc = new SimpleCallback(form.L2Window_ScreenshotUpdate);

            form.Window.ProgressBindings.ScreenshotUpdate += sc;
            form.Window.ProgressBindings.RefreshScreenshot();
            form.updateWhoList();
            form.ShowDialog();
            window.ProgressBindings.ScreenshotUpdate -= sc;
        }
예제 #18
0
        /// <summary>
        /// Saves the email for the player data
        /// </summary>
        /// <param name="callback"></param>
        public static void Identify(string email, SimpleCallback callback)
        {
            string identifyUrl = string.Format(
                "/games/{0}/player/identify",
                Proba.Configuration.GameId
                );

            Request request = new Request(identifyUrl);

            request
            .AddParam("email", email)
            .Post()
            .onFinish += (r) => {
                BaseResponse res = JsonUtility.FromJson <BaseResponse>(r.Response);
                if (res.success)
                {
                    callback();
                }
            };
        }
예제 #19
0
        /// <summary>
        /// Publish a message to a given subject, with optional reply subject and completion block.
        /// </summary>
        /// <param name="subject">the subject to publish to</param>
        /// <param name="callback">server callback</param>
        /// <param name="msg">the message to publish</param>
        /// <param name="optReply">replay subject</param>
        public void Publish(string subject, SimpleCallback callback, string msg, string optReply)
        {
            lock (this.publishLock)
            {
                if (msg == null)
                {
                    throw new ArgumentNullException("msg");
                }

                if (string.IsNullOrEmpty(subject))
                {
                    return;
                }

                this.SendCommand(string.Format(CultureInfo.InvariantCulture, "PUB {0} {1} {2}{3}{4}{5}", subject, optReply, msg.Length, Resource.CRLF, msg, Resource.CRLF));
                if (callback != null)
                {
                    this.QueueServer(callback);
                }
            }
        }
예제 #20
0
        /// <summary>
        /// Spend an amount of credits
        /// </summary>
        /// <param name="credits">Amount of credits</param>
        public void Spend(int credits, SimpleCallback callback = null)
        {
            string spendCreditsUrl = string.Format(
                "/games/{0}/player/spend",
                Proba.Configuration.GameId
                );

            Request request = new Request(spendCreditsUrl);

            request.AddParam("amount", credits);

            // Send request
            request
            .Post()
            .onFinish += (r) => {
                if (callback != null)
                {
                    BaseResponse res = JsonUtility.FromJson <BaseResponse>(r.Response);
                    callback(res);
                }
            };;
        }
예제 #21
0
        public void Publish(string replyTo, string payload, SimpleCallback block)
        {
            Logger.Info("reply_to: {0}: payload: {1}", replyTo, payload);

            string unencrypted = string.Empty;

            if (this.Credentials != null)
            {
                unencrypted = payload;
                payload     = this.Encrypt(replyTo, payload);
            }

            //todo: vladi: encode JSON;
            //YamlNode json =payload;

            // TODO figure out if we want to try to scale down the message instead
            // of generating an exception
            //if (json.Bytesize < NATS_MAX_PAYLOAD_SIZE)
            //{
            try
            {
                this.Nats.Publish(replyTo, block, payload);
            }
            catch (Exception ex)
            {
                Logger.Error("Error while publishing to nats");
            }
            //}
            //else
            //{
            //    string msg = "message > NATS_MAX_PAYLOAD, stored in blobstore";
            //    string original = this.Credentials != null ? payload : unencrypted;
            //    RemoteException exception = new RemoteException(msg, null, original);
            //    Logger.Fatal(msg);
            //    // todo: vladi: fix exception serialization
            //    this.Nats.Publish(replyTo, block, exception.ToHash().ToString());
            //}
        }
예제 #22
0
        public DebugDraw()
        {
            _drawAabb         = new DrawAabbUnmanagedDelegate(DrawAabb);
            _drawArc          = new DrawArcUnmanagedDelegate(DrawArc);
            _drawBox          = new DrawBoxUnmanagedDelegate(DrawBox);
            _drawCapsule      = new DrawCapsuleUnmanagedDelegate(DrawCapsule);
            _drawCone         = new DrawConeUnmanagedDelegate(DrawCone);
            _drawContactPoint = new DrawContactPointUnmanagedDelegate(DrawContactPoint);
            _drawCylinder     = new DrawCylinderUnmanagedDelegate(DrawCylinder);
            _drawLine         = new DrawLineUnmanagedDelegate(DrawLine);
            _drawPlane        = new DrawPlaneUnmanagedDelegate(DrawPlane);
            _drawSphere       = new DrawSphereUnmanagedDelegate(DrawSphere);
            _drawSpherePatch  = new DrawSpherePatchUnmanagedDelegate(DrawSpherePatch);
            _drawTransform    = new DrawTransformUnmanagedDelegate(DrawTransform);
            _drawTriangle     = new DrawTriangleUnmanagedDelegate(DrawTriangle);
            _getDebugMode     = new GetDebugModeUnmanagedDelegate(GetDebugModeUnmanaged);
            _cb = new SimpleCallback(SimpleCallbackUnmanaged);

            IntPtr native = btIDebugDrawWrapper_new(
                GCHandle.ToIntPtr(GCHandle.Alloc(this)),
                Marshal.GetFunctionPointerForDelegate(_drawAabb),
                Marshal.GetFunctionPointerForDelegate(_drawArc),
                Marshal.GetFunctionPointerForDelegate(_drawBox),
                Marshal.GetFunctionPointerForDelegate(_drawCapsule),
                Marshal.GetFunctionPointerForDelegate(_drawCone),
                Marshal.GetFunctionPointerForDelegate(_drawContactPoint),
                Marshal.GetFunctionPointerForDelegate(_drawCylinder),
                Marshal.GetFunctionPointerForDelegate(_drawLine),
                Marshal.GetFunctionPointerForDelegate(_drawPlane),
                Marshal.GetFunctionPointerForDelegate(_drawSphere),
                Marshal.GetFunctionPointerForDelegate(_drawSpherePatch),
                Marshal.GetFunctionPointerForDelegate(_drawTransform),
                Marshal.GetFunctionPointerForDelegate(_drawTriangle),
                Marshal.GetFunctionPointerForDelegate(_getDebugMode),
                Marshal.GetFunctionPointerForDelegate(_cb));

            InitializeUserOwned(native);
        }
예제 #23
0
        /// <summary>
        /// Save a property into the properties list for this player
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public void SaveProperty(string name, string value, SimpleCallback callback = null)
        {
            string savePropertyUrl = string.Format(
                "/games/{0}/player/properties",
                Proba.Configuration.GameId
                );

            Request request = new Request(savePropertyUrl);

            request.AddParam("name", name);
            request.AddParam("value", value);

            // Send request
            request
            .Post()
            .onFinish += (r) => {
                if (callback != null)
                {
                    BaseResponse res = JsonUtility.FromJson <BaseResponse>(r.Response);
                    callback(res);
                }
            };;
        }
예제 #24
0
 private static extern void reply_during_call(SimpleCallback callback);
예제 #25
0
        /// <summary>
        /// Publish a message to a given subject, with optional reply subject and completion block. 
        /// </summary>
        /// <param name="subject">the subject to publish to</param>
        /// <param name="callback">server callback</param>
        /// <param name="msg">the message to publish</param>
        /// <param name="optReply">replay subject</param>
        public void Publish(string subject, SimpleCallback callback, string msg, string optReply)
        {
            lock (this.publishLock)
            {
                if (msg == null)
                {
                    throw new ArgumentNullException("msg");
                }

                if (string.IsNullOrEmpty(subject))
                {
                    return;
                }

                this.SendCommand(string.Format(CultureInfo.InvariantCulture, "PUB {0} {1} {2}{3}{4}{5}", subject, optReply, msg.Length, Resource.CRLF, msg, Resource.CRLF));
                if (callback != null)
                {
                    this.QueueServer(callback);
                }
            }
        }
예제 #26
0
 public static void DoSomethingAsynchronous(SimpleCallback simpleCallback)
 {
     // ... do something ...
     simpleCallback(true);
 }
예제 #27
0
 public void GetScreenshot(SimpleCallback callback)
 {
     RefreshScreenshot();
 }
예제 #28
0
 void OnApplicationQuit() {
   set_recurring_reply(gameObject.GetHashCode(), null);
   _recurring_callback_holder = null;
   set_recurring_data_push(gameObject.GetHashCode(), null);
   _recurring_data_push_holder = null;
 }
예제 #29
0
 /// <summary>
 /// Publish a message to a given subject, with optional reply subject and completion block. 
 /// </summary>
 /// <param name="subject">the subject to publish to</param>
 /// <param name="callback">server callback</param>
 public void Publish(string subject, SimpleCallback callback)
 {
     this.Publish(subject, callback, Resource.EMPTYMSG, null);
 }
		public void DelegateMethodTest () 
		{
			SimpleCallback callback = new SimpleCallback (SimpleCallbackImpl);
			method = GetMethodForTest ("SimpleCallbackImpl");
			messageCollection = rule.CheckMethod (method, new MinimalRunner ());
			Assert.IsNull (messageCollection);
		}
예제 #31
0
        internal void InitTarget(IDebugDraw target)
        {
            _drawAabb = new DrawAabbUnmanagedDelegate(target.DrawAabb);
            _drawArc = new DrawArcUnmanagedDelegate(target.DrawArc);
            _drawBox = new DrawBoxUnmanagedDelegate(target.DrawBox);
            _drawCapsule = new DrawCapsuleUnmanagedDelegate(target.DrawCapsule);
            _drawCone = new DrawConeUnmanagedDelegate(target.DrawCone);
            _drawContactPoint = new DrawContactPointUnmanagedDelegate(target.DrawContactPoint);
            _drawCylinder = new DrawCylinderUnmanagedDelegate(target.DrawCylinder);
            _drawLine = new DrawLineUnmanagedDelegate(target.DrawLine);
            _drawPlane = new DrawPlaneUnmanagedDelegate(target.DrawPlane);
            _drawSphere = new DrawSphereUnmanagedDelegate(target.DrawSphere);
            _drawSpherePatch = new DrawSpherePatchUnmanagedDelegate(target.DrawSpherePatch);
            _drawTransform = new DrawTransformUnmanagedDelegate(target.DrawTransform);
            _drawTriangle = new DrawTriangleUnmanagedDelegate(target.DrawTriangle);
            _getDebugMode = new GetDebugModeUnmanagedDelegate(GetDebugModeUnmanaged);
            _cb = new SimpleCallback(SimpleCallbackUnmanaged);

            _native = btIDebugDrawWrapper_new(
                GCHandle.ToIntPtr(GCHandle.Alloc(this)),
                Marshal.GetFunctionPointerForDelegate(_drawAabb),
                Marshal.GetFunctionPointerForDelegate(_drawArc),
                Marshal.GetFunctionPointerForDelegate(_drawBox),
                Marshal.GetFunctionPointerForDelegate(_drawCapsule),
                Marshal.GetFunctionPointerForDelegate(_drawCone),
                Marshal.GetFunctionPointerForDelegate(_drawContactPoint),
                Marshal.GetFunctionPointerForDelegate(_drawCylinder),
                Marshal.GetFunctionPointerForDelegate(_drawLine),
                Marshal.GetFunctionPointerForDelegate(_drawPlane),
                Marshal.GetFunctionPointerForDelegate(_drawSphere),
                Marshal.GetFunctionPointerForDelegate(_drawSpherePatch),
                Marshal.GetFunctionPointerForDelegate(_drawTransform),
                Marshal.GetFunctionPointerForDelegate(_drawTriangle),
                Marshal.GetFunctionPointerForDelegate(_getDebugMode),
                Marshal.GetFunctionPointerForDelegate(_cb));
        }
예제 #32
0
 /// <summary>
 /// Publish a message to a given subject, with optional reply subject and completion block.
 /// </summary>
 /// <param name="subject">the subject to publish to</param>
 /// <param name="callback">server callback</param>
 public void Publish(string subject, SimpleCallback callback)
 {
     this.Publish(subject, callback, Resource.EMPTYMSG, null);
 }
예제 #33
0
 public void GetScreenshot(SimpleCallback callback)
 {
     RefreshScreenshot();
 }
예제 #34
0
 void OnDestroy() {
   set_recurring_reply(gameObject.GetHashCode(), null);
   _recurring_callback_holder = null;
   set_recurring_data_push(gameObject.GetHashCode(), null);
   _recurring_data_push_holder = null;
 }
예제 #35
0
 /// <summary>
 /// Publish a message to a given subject, with optional reply subject and completion block. 
 /// </summary>
 /// <param name="subject">the subject to publish to</param>
 /// <param name="callback">server callback</param>
 /// <param name="msg">the message to publish</param>
 public void Publish(string subject, SimpleCallback callback, string msg)
 {
     this.Publish(subject, callback, msg, null);
 }
예제 #36
0
        /// <summary>
        /// Queues the server.
        /// </summary>
        /// <param name="callback">The callback.</param>
        private void QueueServer(SimpleCallback callback)
        {
            if (callback == null)
            {
                return;
            }

            this.pongs.Enqueue(callback);
            this.SendCommand(this.resource.PINGREQUEST);
        }
예제 #37
0
 public void GetScreenshot(SimpleCallback callback)
 {
     ScreenshotUpdate += callback;
     RefreshScreenshot();
 }
예제 #38
0
 private static extern void set_recurring_reply(int objectHash, SimpleCallback callback);
예제 #39
0
 public void GetScreenshot(SimpleCallback callback)
 {
     ScreenshotUpdate += callback;
     RefreshScreenshot();
 }
 public void AnonymousMethodWithUnusedParameters()
 {
     SimpleCallback callback = delegate(int x) {
         //Empty
     };
 }
예제 #41
0
    IEnumerator StartsPerClassTask( SimpleCallback callThis )
    {
        Debug.Log( "starting" );
        yield return new WaitForSeconds(2);
        Debug.Log( "finishing" );

        //this is quite specific
        callThis.PersonalCall();
    }
예제 #42
0
		public void CreateMoreComplexCallable()
		{
			EasyType typebuilder = new EasyType( module, "mytype" );

			ArgumentReference arg1 = new ArgumentReference( typeof(int) );
			ArgumentReference arg2 = new ArgumentReference( typeof(DateTime) );
			ArgumentReference arg3 = new ArgumentReference( typeof(object) );
			EasyCallable callable = typebuilder.CreateCallable( 
				new ReturnReferenceExpression(typeof(string)), 
				arg1, arg2, arg3 );

			FieldReference field1 = typebuilder.CreateField( "field1", callable.TypeBuilder );

			SimpleCallback sc = new SimpleCallback();

			ArgumentReference arg = new ArgumentReference( typeof(SimpleCallback) );
			EasyConstructor constructor = typebuilder.CreateConstructor( arg );
			constructor.CodeBuilder.InvokeBaseConstructor();

			constructor.CodeBuilder.AddStatement( new AssignStatement(field1, 
				new NewInstanceExpression( callable, 
				arg.ToExpression(), 
				new MethodPointerExpression( arg, typeof(SimpleCallback).GetMethod("RunAs") ) ) ) );
			
			constructor.CodeBuilder.AddStatement( new ReturnStatement() );

			arg1 = new ArgumentReference( typeof(int) );
			arg2 = new ArgumentReference( typeof(DateTime) );
			arg3 = new ArgumentReference( typeof(object) );
			
			ReturnReferenceExpression ret1 = new ReturnReferenceExpression(typeof(string));
			
			EasyMethod getField1 = typebuilder.CreateMethod( "Exec", ret1, arg1, arg2, arg3 );
			getField1.CodeBuilder.AddStatement( 
				new ReturnStatement( 
					new ConvertExpression( typeof(String), 
						new MethodInvocationExpression( field1, 
							callable.Callmethod, 
							new ReferencesToObjectArrayExpression(arg1, arg2, arg3) ) ) ) );

			Type newType = typebuilder.BuildType();

			RunPEVerify();
			
			object instance = Activator.CreateInstance( newType, new object[] { sc } );

			MethodInfo method = instance.GetType().GetMethod("Exec");
			object result = method.Invoke( instance, new object[] { 1, DateTime.Now, "" } );
			Assert.AreEqual( "hello2", result );
		}
예제 #43
0
 /// <summary>
 /// Publish a message to a given subject, with optional reply subject and completion block.
 /// </summary>
 /// <param name="subject">the subject to publish to</param>
 /// <param name="callback">server callback</param>
 /// <param name="msg">the message to publish</param>
 public void Publish(string subject, SimpleCallback callback, string msg)
 {
     this.Publish(subject, callback, msg, null);
 }
예제 #44
0
        public void TC015_MultipleResponseCallback()
        {
            bool errorThrown = false;
            List<int> expected = new List<int>();
            List<int> response = new List<int>();

            AutoResetEvent resetEvent = new AutoResetEvent(false);

            using (IReactor natsClient = ReactorFactory.GetReactor(typeof(Reactor)))
            {
                natsClient.OnError += new EventHandler<ReactorErrorEventArgs>(delegate(object sender, ReactorErrorEventArgs args)
                {
                    errorThrown = true;
                    resetEvent.Set();
                });

                natsClient.Start(natsEndpoint);

                SimpleCallback[] delegates = new SimpleCallback[] {
                delegate() { response.Add(0); },
                delegate() { response.Add(1); },
                delegate() { response.Add(2); },
                delegate() { response.Add(3); },
                delegate() { response.Add(4); },
                delegate() { response.Add(5); },
                delegate() { response.Add(6); },
                delegate() { response.Add(7); },
                delegate() { response.Add(8); },
                delegate() { response.Add(9); },
                delegate() { response.Add(10); },
                delegate() { response.Add(11); },
                delegate() { response.Add(12); },
                delegate() { response.Add(13); },
                delegate() { response.Add(14); }
                };

                for (int i = 0; i < 15; i++)
                {
                    expected.Add(i);
                    natsClient.Publish("foo", delegates[i]);
                }

                natsClient.Publish("foo", delegate()
                {
                    resetEvent.Set();
                });

                resetEvent.WaitOne(5000);
                natsClient.Close();
            }
            Assert.IsFalse(errorThrown);

            for (int i = 0; i < 15; i++)
            {
                Assert.AreEqual(expected[i], response[i]);
            }
        }
예제 #45
0
        private void ReceiveData(byte[] data, int bytesRead)
        {
            if (this.buf == null)
            {
                this.buf = new List <byte>(bytesRead);
            }

            this.buf.AddRange(data.Take(bytesRead));

            while (this.buf != null)
            {
                switch (this.parseState)
                {
                case ParseState.AwaitingControlLine:
                {
                    ASCIIEncoding ascii     = new ASCIIEncoding();
                    string        strBuffer = ascii.GetString(this.buf.ToArray());

                    if (this.resource.MSG.IsMatch(strBuffer))
                    {
                        Match match = this.resource.MSG.Match(strBuffer);
                        strBuffer           = this.resource.MSG.Replace(strBuffer, string.Empty);
                        this.subscriptionId = Convert.ToInt32(match.Groups[2].Value, CultureInfo.InvariantCulture);
                        this.reply          = match.Groups[4].Value;
                        this.needed         = Convert.ToInt32(match.Groups[5].Value, CultureInfo.InvariantCulture);
                        this.parseState     = ParseState.AwaitingMsgPayload;
                    }
                    else if (this.resource.OK.IsMatch(strBuffer))
                    {
                        strBuffer = this.resource.OK.Replace(strBuffer, string.Empty);
                    }
                    else if (this.resource.ERR.IsMatch(strBuffer))
                    {
                        if (this.OnError != null)
                        {
                            this.OnError(this, new ReactorErrorEventArgs(this.resource.ERR.Match(strBuffer).Groups[1].Value));
                        }

                        strBuffer = this.resource.ERR.Replace(strBuffer, string.Empty);
                    }
                    else if (this.resource.PING.IsMatch(strBuffer))
                    {
                        this.SendCommand(this.resource.PONGRESPONSE);
                        strBuffer = this.resource.PING.Replace(strBuffer, string.Empty);
                    }
                    else if (this.resource.PONG.IsMatch(strBuffer))
                    {
                        if (this.pongs.Count > 0)
                        {
                            SimpleCallback callback = this.pongs.Dequeue();

                            try
                            {
                                callback();
                            }
                            catch (Exception ex)
                            {
                                if (this.OnError != null)
                                {
                                    this.OnError(this, new ReactorErrorEventArgs(Language.CallbackException, ex));
                                }
                            }
                        }

                        strBuffer = this.resource.PONG.Replace(strBuffer, string.Empty);
                    }
                    else if (this.resource.INFO.IsMatch(strBuffer))
                    {
                        this.serverInfo = JsonConvertibleObject.ObjectToValue <Dictionary <string, object> >(JsonConvertibleObject.DeserializeFromJson(this.resource.INFO.Match(strBuffer).Groups[1].Value));
                        strBuffer       = this.resource.INFO.Replace(strBuffer, string.Empty);
                    }
                    else if (this.resource.UNKNOWN.IsMatch(strBuffer))
                    {
                        if (this.OnError != null)
                        {
                            this.OnError(this, new ReactorErrorEventArgs(Language.ERRUnknownProtocol + this.resource.UNKNOWN.Match(strBuffer).Value));
                        }

                        strBuffer = this.resource.UNKNOWN.Replace(strBuffer, string.Empty);
                    }
                    else
                    {
                        this.buf = ascii.GetBytes(strBuffer).ToList();
                        return;
                    }

                    this.buf = ascii.GetBytes(strBuffer).ToList();
                    if (this.buf != null && this.buf.Count == 0)
                    {
                        this.buf = null;
                    }
                }

                break;

                case ParseState.AwaitingMsgPayload:
                {
                    if (this.buf.Count < (this.needed + Resource.CRLF.Length))
                    {
                        return;
                    }

                    ASCIIEncoding ascii     = new ASCIIEncoding();
                    string        strBuffer = ascii.GetString(this.buf.ToArray());

                    this.OnMessage(this.subscriptionId, this.reply, strBuffer.Substring(0, this.needed));

                    strBuffer = strBuffer.Substring(this.needed + Resource.CRLF.Length);

                    this.reply          = string.Empty;
                    this.subscriptionId = this.needed = 0;

                    this.parseState = ParseState.AwaitingControlLine;

                    this.buf = ascii.GetBytes(strBuffer).ToList();
                    if (this.buf != null && this.buf.Count == 0)
                    {
                        this.buf = null;
                    }
                }

                break;
                }
            }
        }
 private static extern void SimpleCallbackFun(SimpleCallback c);
    //-------------------  Section 2 test functions   -------------------------------------------------
    private void Run2_1()
    {
        SimpleCallback sc = new SimpleCallback(SimpleCallbackUnityFun);

        SimpleCallbackFun(sc);
    }
예제 #48
0
        public void Publish(string replyTo, string payload, SimpleCallback block)
        {
            Logger.Info("reply_to: {0}: payload: {1}", replyTo, payload);

            string unencrypted = string.Empty;
            if (this.Credentials != null)
            {
                unencrypted = payload;
                payload = this.Encrypt(replyTo, payload);
            }

            //todo: vladi: encode JSON;
            //YamlNode json =payload;

            // TODO figure out if we want to try to scale down the message instead
            // of generating an exception
            //if (json.Bytesize < NATS_MAX_PAYLOAD_SIZE)
            //{
            try
            {
                this.Nats.Publish(replyTo, block, payload);
            }
            catch (Exception ex)
            {
                Logger.Error("Error while publishing to nats");
            }
            //}
            //else
            //{
            //    string msg = "message > NATS_MAX_PAYLOAD, stored in blobstore";
            //    string original = this.Credentials != null ? payload : unencrypted;
            //    RemoteException exception = new RemoteException(msg, null, original);
            //    Logger.Fatal(msg);
            //    // todo: vladi: fix exception serialization
            //    this.Nats.Publish(replyTo, block, exception.ToHash().ToString());
            //}
        }