Welcome!

Java IoT Authors: Stackify Blog, Nitin Donde, Elizabeth White, Liz McMillan, Kevin Benedict

Related Topics: Java IoT

Java IoT: Article

Managing Objects Between Java and C

Building the Java API on top of the native API

If you've ever used JNI, you know how to manage the primitive data types between Java and the native language. As you delve into JNI, particularly when developing a Java API on top of a native API, you need to know how to manage the objects between Java and the native language. This article takes you to the next level and walks you through the step-by-step process of managing the objects between Java and C.

Why JNI
Platform independence and flexibility are the popular buzzwords in the industry and programmers want to prune their code. Everyone wants to program in their favorite language, unfortunately you can't always stick to your selection, as some components of an application have to be programmed in a completely different language or some components are only available in a different language. The solution to these situations is JNI. The Java Native Interface (JNI) is the native programming interface for Java that's part of the JDK. JNI allows Java code that runs within a Java Virtual Machine to operate with applications and libraries written in other languages, such as C or C++.

In addition, if you want to do some system-level programming with Java, you'll definitely end up using JNI somewhere. JNI is essential for bridging the gap between Java and the native functions. It allows you to write some code in a native language and then talk to that native code through Java.

Real-Life Scenario
When I wanted to develop a wireless mail solution for a particular mail server, I realized that Java was well suited for developing wireless solutions; however, that mail server had a C API, not a Java API. I then started writing the Java API using JNI on top of the C API. The main obstacle I faced was while passing the objects between Java and C. This article explains how I overcame this obstacle. By the end of this article you'll be familiar with the process of managing objects between Java and C. To understand this article you should be familiar with the basic concepts in JNI (see the Resources section for the JNI documentation).

Why Do You Need to Manage the Objects Between Java and C?
If you're developing the API, sometimes you may need to store an object in Java that you created in C; for example, a mail API. First log into the server with a username and password, then you get the session. Say you wanted to store that session in Java for later use, e.g., for reading or writing an e-mail. If you save the session in Java, you can then pass this session to C to read or write e-mail, etc.

Managing the Objects Between Java and C
You should already know how to pass the primitive types between Java and C (otherwise see the Resources section); it's straightforward. Unfortunately you can't directly convert the objects between Java and C like the primitives. You can indirectly store the C object memory location in Java through a long variable. Later, if you want to pass that object to C, simply pass the memory location. From the memory location you can retrieve the C object.

To maintain the same object in Java and C, create some object in Java and declare a long variable in it to hold the memory location of the object created in C.

I'll illustrate this in detail with the mail example. The first part explains how to fill the Java object from C and the second part explains how to get the C object out of the Java object (to help you understand, I bifurcated each section into a Java side and a C side).

Filling a Java Object from a C Object
Figure 1 shows the different steps involved in this process.

The following example discusses these steps in more detail:

  • Declare a global long variable:

    public long nativeSession;

  • Declare a native method:

    public void native jniLogin(String server, String userName, String password);

  • Define a Java API method to expose the native method:

    
    	public void login(String server, String userName, String password) {
    		jniLogin(server, userName, String password);
    	}
    

    Listing 1 provides a nativeSession variable, which will hold the session object that actually gets created in C through the native method jniLogin. Once we create the session object in C, we'll fill this nativeSession variable that's declared in Listing 1 with the memory location of the C object. I'll discuss this in-depth later.

    I won't explain the step about creating the header file out of a Java file using the javah command (see Resources for this information), so I'll jump directly to the C implementation of this native method.

    Let's see the C implementation of the native method jniLogin:

  • Create the native Object:

    
    	Session msession = NULL;
                connect(mserver, muserName, mpassword, &msession);
    

  • Get the memory location of the object:

    jlong sessionLocation = (jlong)msession;

  • Get the Java object from the parameters:

    jclass cls = (*env)->GetObjectClass(env, obj);

  • Fill the Java objects long variable with a memory location:

    
    	jfieldID fid =(*env)->GetFieldID(env, cls,"nativeSession","J");
                (*env)->SetLongField(env,obj,fid,sessionLocation);
    

    In line 8 of Listing 2, I'm declaring the Session(C) object. In line 14, to connect to a particular mail server, we're passing the values of the server, the user name, and the password to the connect method. If the given user name and password is valid, the msession object gets filled. Note that the function "Connect" is already defined in the C API of the mail server. Now we have the session object that logged into the server in C. In line 15 we're getting the memory location of the msession object. When you do (jlong)msession, it gives the memory location of the msession object. In line 20 we are getting the Java object that called this C function. In line 21, we're getting the long field(variable) "nativeSession" that we declared in Session(Java). In line 20 we're setting the long variable with the variable sessionLocation. Now the variable nativeSession of Session(Java) object holds the memory location of the msession(C) object.

    Getting the C Object Back Out of the Java Object
    Figure 2 explains the different steps involved in this process.

    The following example provides a clearer picture:

  • Declare the native method with the long variable that holds the memory location of the native object through the native method:

    public void native jniSendMail(Object o, String to, String subject, String body);

  • Define a Java API method to expose the native method and pass the long variable to the native method:

    
    public void sendMail(String to, String subject, String body) {
    	jniSendMail(this, to, subject, body);
    }
    

    Let's say you wanted to send an e-mail with the session that logged in through the login method. For that we are passing the session object (with "this" keyword) to the jniSendMail method in Listing 3. Notice that session object has the nativeSession variable that holds the memory location of the native session object. With that we can send the e-mail. Let's see how we can get the native session back from this object in the next steps:

  • Get the Java object from the parameters:

    jclass cls = (*env)->GetObjectClass(env, sessionobj);

  • Get the long variable from the Java object that holds the memory location of the native object:

    
    	jfieldID fid =(*env)->GetFieldID(env, cls,"nativeSession","J");
                jlong session = (*env)->GetLongField(env,obj,fid);
    

  • Get the native object from that memory location and reuse it:

    
    	Session *  msession = (Session)session;
                sendMail(msession, mto, msubject, mbody);
    

    In line 14 of Listing 4, we're getting the Session(Java) class. In line 15, we're getting the variable nativeSession. Line 16 provides the value of the nativeSession variable that has the memory location of the native session. Line 18 has the C object from the memory location, since the long variable session holds the memory location of the native session object. When you typecast with (Session)session, it reads the object from the memory location. Now we have the C object. With this in line 19 we are calling the SendMail function with the values msession, mto, msubject, and mbody, which sends the e-mail to the address specified in the field "mto". Note that "SendMail" is the function that's already defined in the C API of the mail server.

    Resources

  • Java Native Interface tutorial: http://java.sun.com/docs/books/tutorial/native1.1/TOC.html
  • Java Native Interface Specification: http://java.sun.com/j2se/1.4.2/docs/guide/jni/
  • More Stories By Hari Gottipati

    Hari K Gottipati is a software professional, consultant, speaker and freelance writer who specializes in Java, mobile computing, cloud computing, virtualization and Ajax. Proven Java enterprise lead, competitive analyst, technical architect and loves coding. Expert in analyzing market landscape for startup ideas and molding them into successful products with the technical/competitive advantage. Regularly writes for Syscon media, O'Reilly publications and his quotes can be often found in various technology news/magazines. Well known blogger and his blogs can be found at sys-con.com, onjava.com and xml.com. Speaks at various events on latest technologies including Mobile, Cloud computing, Ajax, Web 2.0, Web OS and of course Java. Hari serves on technical advisory board for various small to medium size companies where he provides technical vision for the future. Worked for many wireless startups, as well as big companies including Yahoo, Travelocity, and Motorola. Passionate about technologies and spends most of his time exploring bleeding edge software technologies.

    Comments (2)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    @ThingsExpo Stories
    "We are focused on SAP running in the clouds, to make this super easy because we believe in the tremendous value of those powerful worlds - SAP and the cloud," explained Frank Stienhans, CTO of Ocean9, Inc., in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
    "We've been engaging with a lot of customers including Panasonic, we've been involved with Cisco and now we're working with the U.S. government - the Department of Homeland Security," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
    Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution and join Akvelon expert and IoT industry leader, Sergey Grebnov, in his session at @ThingsExpo, for an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
    The financial services market is one of the most data-driven industries in the world, yet it’s bogged down by legacy CPU technologies that simply can’t keep up with the task of querying and visualizing billions of records. In his session at 20th Cloud Expo, Karthik Lalithraj, a Principal Solutions Architect at Kinetica, discussed how the advent of advanced in-database analytics on the GPU makes it possible to run sophisticated data science workloads on the same database that is housing the rich...
    IoT is at the core or many Digital Transformation initiatives with the goal of re-inventing a company's business model. We all agree that collecting relevant IoT data will result in massive amounts of data needing to be stored. However, with the rapid development of IoT devices and ongoing business model transformation, we are not able to predict the volume and growth of IoT data. And with the lack of IoT history, traditional methods of IT and infrastructure planning based on the past do not app...
    With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, will examine the regulations and provide insight on how it affects technology, challenges the established rules and will usher in new levels of diligence...
    DX World EXPO, LLC., a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
    In the enterprise today, connected IoT devices are everywhere – both inside and outside corporate environments. The need to identify, manage, control and secure a quickly growing web of connections and outside devices is making the already challenging task of security even more important, and onerous. In his session at @ThingsExpo, Rich Boyer, CISO and Chief Architect for Security at NTT i3, discussed new ways of thinking and the approaches needed to address the emerging challenges of security i...
    Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
    What sort of WebRTC based applications can we expect to see over the next year and beyond? One way to predict development trends is to see what sorts of applications startups are building. In his session at @ThingsExpo, Arin Sime, founder of WebRTC.ventures, discussed the current and likely future trends in WebRTC application development based on real requests for custom applications from real customers, as well as other public sources of information.
    "The Striim platform is a full end-to-end streaming integration and analytics platform that is middleware that covers a lot of different use cases," explained Steve Wilkes, Founder and CTO at Striim, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
    SYS-CON Events announced today that Calligo, an innovative cloud service provider offering mid-sized companies the highest levels of data privacy and security, has been named "Bronze Sponsor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalised support service from its globally located cloud plat...
    SYS-CON Events announced today that Massive Networks will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
    SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
    SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
    While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
    "DX encompasses the continuing technology revolution, and is addressing society's most important issues throughout the entire $78 trillion 21st-century global economy," said Roger Strukhoff, Conference Chair. "DX World Expo has organized these issues along 10 tracks with more than 150 of the world's top speakers coming to Istanbul to help change the world."
    "We provide IoT solutions. We provide the most compatible solutions for many applications. Our solutions are industry agnostic and also protocol agnostic," explained Richard Han, Head of Sales and Marketing and Engineering at Systena America, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
    "MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
    SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.