JNA using callbacks to implement event listeners in Java-observer mode

Source: Internet
Author: User

(1) interface header file in C interface

#pragmaOnce#include<iostream>#include<vector>#include<core/core.hpp>#include#include#ifdef videoposition_exports#defineVideoposition_api __declspec (dllexport)#else#defineVideoposition_api __declspec (dllimport)#endif //Vision_exportsusing namespacestd;using namespaceCv;typedefvoid(*callback_colorpos) (intColorfloatFxfloatFY); typedefvoid(*callback_imageok) (intstatus);extern "C"  intVideoposition_api colorpos (callback_colorpos getcolorpos,callback_imageok getimagesttus);extern "C"  intVideoposition_api Opencamera (intindex);extern "C"  intVideoposition_api Closecamera ();

As we can see, there are three functions in the oral file, and there are two callback types for the parameters of one function.

(2) Implementation of JNA callback class in Java

 Packagecom.wxyz.scene_demonstration;ImportCom.sun.jna.Callback;/*** Round cake color and Position Callback interface * *@authorDengchaoqun **/ Public InterfaceColorposlistenerextendsCallback {//defines an interface that inherits from the JNA callback class, corresponding to the Callback_colorpos callback in the header file above    /*** Callback Method * *@paramColor * Round cake colour *@paramX * x-axis coordinates of the PIE *@paramY * The y-axis coordinates of the pie*/     Public voidStatus (intColorfloatXfloaty);//corresponds to three parameters in the callback interface in C (corresponding to the three parameters in the Callback_colorpos callback in the header file above ))
}

(3) Java callback Interface implementation, implementation Colorposlistener this interface, the implementation of the status method, when the dynamic library has data, the data will be passed to the status method in the three parameters, so that the Java side can listen to the data in the dynamic library, and processing.

Java corresponds to the dynamic library interface as follows

 Packagecom.wxyz.scene_demonstration;Importcom.sun.jna.Library;Importcom.sun.jna.Native;/*** Dynamic Regular interface * *@authorDengchaoqun **/ Public InterfaceScenedemo2apiextendsLibrary {scenedemo2api INSTANCE= (SCENEDEMO2API) native.loadlibrary ("Videoposition", Scenedemo2api.class);  Public intOpencamera (intItem);//Open the Camera interface method     Public intColorpos (Colorposlistener getcolorpos, Imageoklistener GetImage);//callback method to get data     Public intClosecamera ();//How to turn off the camera}

The Java interface corresponds to the following implementation class, as well as using the demo as follows

 Packagecom.wxyz.scene_demonstration; @SuppressWarnings ("Unused") Public classScenedemo2control {Private Static BooleanCamerastatus =true;//the state of the camera is turned off by default    Private Static Final floatY_point = 80.0f;//The coordinate values of the y-axis direction of the image recognition origin in the manipulator coordinate system    Private Static Final floatZ_point = -312.5f;//The coordinate value of the z-axis direction of the image recognition origin in the manipulator coordinate play, that is, the coordinate value of the sucking round cake    Private Static Final floats = 339.5f;//The distance from the x-axis of the origin of the robotic arm, which is used for calculating the time of the pie data sending point.     /*** Callback listening camera back to the round cake data, and whether the picture is written well listening *@paramListener * Listener, users need to implement a Colorposlistener interface, when the data returned can be real-time access to the dynamic library callback data * image * Listener, users need to implement a Imageoklistener interface when using, 20ms take a picture, when the picture is written, return 1, * Updatable interface ImageView *@returnstatus Code This method is a time-lapse method that will be executed after the camera is opened and will not return 1 values until the camera is closed .*/     Public Static intGetcolorpos (Colorposlistener Listener, Imageoklistener image) {if(Camerastatus = =false) {System.out.println ("The camera is not open, please open the camera successfully!" "); return-1; } Else {            intStatus =SceneDemo2API.INSTANCE.ColorPos (listener, image); returnstatus; }    }    /*** Turn on the camera * *@paramItem * Indicates which camera, starting from 0 *@returnturn on the camera state, 1 means open failed, 0 means open successful*/     Public Static intOpencamera (intItem) {        intStatus =SceneDemo2API.INSTANCE.OpenCamera (item); if(Status = = 0) {Camerastatus=true; System.out.println ("The camera turned on successfully!" "); } Else{camerastatus=true; System.out.println ("Camera Open failed!" "); }        returnstatus; }    /*** How to turn off the camera * *@returnstatus, 1 indicates shutdown failed, 0 indicates shutdown succeeded*/     Public Static intClosecamera () {intStatus =SceneDemo2API.INSTANCE.CloseCamera (); if(Status = = 0) {Camerastatus=true; System.out.println ("The camera shuts down successfully!" "); } Else{camerastatus=true; System.out.println ("Camera off failed!" "); }        returnstatus; }    //Demo     Public Static voidMain (string[] args) {Opencamera (1); Getcolorpos (NewColorposlistener () {@Override Public voidStatus (intColorfloatXfloaty) {//color correspondence, 0 red, 1 green, 2 blue, 3 yellow, 4 white, 5 purplex = Math.Round (x);//The x-coordinate of the suction point is fixed and needs to be based on the actual position of the suction ball.y = Math.Round (y)-Y_point; if(color = = 1) {//assume that the two colors are each of//Call the motion method, the nozzle suction cake, movement to the specified side                } Else if(Color = = 2) {                    //Call the motion method, the nozzle suction cake, movement to the specified side} System.out.println (x+ "::" +y); }        }, NewImageoklistener () {@Override Public voidGetImage (intImgready) {                //TODO auto-generated Method Stub                if(Imgready = = 1) {//picture's written.//Update the value of ImageView}Else if(Imgready = = 0) {//writing a picture                }            }        });    Closecamera (); }}

JNA using callbacks to implement event listeners in Java-observer mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.