Awhile back I had to create a JNI wrapper for a C++ class that uses a proprietary core C API. Rewriting everything including the core API in Java would be safer and perform better but in this case not duplicating code was more important. I couldn't find a clear code example containing everything that was needed to 1) make the JNI work at all and 2) wrap a class and call its non-static member function, so I'm putting this here in case it might help someone else.
There are two source files you'll need to write:
Here is an example, A.java:
There are three native methods declared in A.java: one that will create an instance of the C++ class, one that calls a member function of the class, and one that destroys the instance. There is a member variable, ptr_, which stores the pointer to the A instance that's created outside the JVM. You need this to call the member function, getResult(). You also need it to destroy the A instance when you're done. Once you have your Java class written you'll need to:
The header contains function prototypes that you'll need to provide implementations for in a C++ source file.
Here is the example JNI code, A.cc:
The code includes A.hh, the header for the C++ class you're wrapping. All the use of the C++ class is here. Then, A.cc needs to be compiled and linked with the library you're wrapping into a new library, for example libAJni.so, that gets loaded by the Java code using System.load() as you saw in A.java earlier. That's pretty much it. You can now use the Java class A to interact with the C++ library libAJni.so which interacts with the C++ library you wanted to wrap in the first place.
There are two source files you'll need to write:
- A Java class that declares native methods, loads the library built using the JNI, and calls native methods.
- JNI code that implements the native methods declared in the Java class and uses the C++ class you're wrapping. You'll build a library with this.
Here is an example, A.java:
package com.company.product.component;
import java.util.Properties;
public class A {
private long ptr_;
private native long createA(long value);
private native void destroyA(long ptr);
private native long getResult(long ptr, byte[] input, long length);
static {
System.loadLibrary("AJni");
}
public A(long value) {
ptr_ = createA(value);
}
/**
* Destroy the A instance created by the JNI.
* This must be called when finished using the A.
*/
public void destroy() {
destroyA(ptr_);
}
/**
* Do something.
*
* @param input The input array
* @param length The length of the input array to process
* @return The result
*/
public long getResult(byte[] input, long length) {
return getResult(ptr_, input, length);
}
}
There are three native methods declared in A.java: one that will create an instance of the C++ class, one that calls a member function of the class, and one that destroys the instance. There is a member variable, ptr_, which stores the pointer to the A instance that's created outside the JVM. You need this to call the member function, getResult(). You also need it to destroy the A instance when you're done. Once you have your Java class written you'll need to:
- Use javac to compile A.java into A.class.
- Run javah on the Java class like this: javah com.company.product.component.A
to generate com_company_product_component_A.h which you'll include in the JNI code.
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_company_product_component_A */
#ifndef _Included_com_company_product_component_A
#define _Included_com_company_product_component_A
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_company_product_component_A
* Method: createA
* Signature: (J)J
*/
JNIEXPORT jlong JNICALL Java_com_company_product_component_A_createA
(JNIEnv *, jobject, jlong);
/*
* Class: com_company_product_component_A
* Method: destroyA
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_com_company_product_component_A_destroyA
(JNIEnv *, jobject, jlong);
/*
* Class: com_company_product_component_A
* Method: getResult
* Signature: (J[BJ)J
*/
JNIEXPORT jlong JNICALL Java_com_company_product_component_A_getResult
(JNIEnv *, jobject, jlong, jbyteArray, jlong);
#ifdef __cplusplus
}
#endif
#endif
The header contains function prototypes that you'll need to provide implementations for in a C++ source file.
Here is the example JNI code, A.cc:
#include "com_company_product_component_A.h"
#include <A.hh>
JNIEXPORT jlong JNICALL Java_com_company_product_component_createA
(JNIEnv *env, jobject obj, jlong value)
{
return reinterpret_cast<jlong>(new A(value));
}
JNIEXPORT void JNICALL Java_com_company_product_component_destroyA
(JNIEnv *env, jobject obj, jlong ptr)
{
A *a = reinterpret_cast<A*>(ptr);
if(a) {
delete a;
}
}
JNIEXPORT jlong JNICALL Java_com_company_product_component_getResult
(JNIEnv *env, jobject obj, jlong ptr, jbyteArray input, jlong length)
{
jbyte *inputArray = env->GetByteArrayElements(input, NULL);
jlong result = reinterpret_cast<A*>(ptr)->
getResult(reinterpret_cast<const char*>(inputArray), length);
env->ReleaseByteArrayElements(input, inputArray, 0);
return result;
}
The code includes A.hh, the header for the C++ class you're wrapping. All the use of the C++ class is here. Then, A.cc needs to be compiled and linked with the library you're wrapping into a new library, for example libAJni.so, that gets loaded by the Java code using System.load() as you saw in A.java earlier. That's pretty much it. You can now use the Java class A to interact with the C++ library libAJni.so which interacts with the C++ library you wanted to wrap in the first place.
A.class --> libAJni.so --> libA.so
Thank You.
ReplyDeleteHi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer Node js Training in Chennai . learn from or Javascript Online Training from India. Nowadays JavaScript has tons of job opportunities on various vertical industry. JavaScript Training in Chennai
DeleteAwesome, worked like a charm!
ReplyDeleteThank you.
Thanks! Would you mind also providing a sample A.cc, for those of us who are complete noobs?
ReplyDeleteThis worked so smoothly, unlike a lot of other solutions. Thanks man!
ReplyDeleteThank you so much.
I tried but something was wrong. I prefered to use a static structure with wy class instance. (like in the following example).
ReplyDeletehttps://github.com/googlesamples/android-ndk/blob/master/audio-echo
Well Said, you have furnished the right information that will be useful to anyone at all time. Thanks for sharing your Ideas.
ReplyDeleteData Science training in Chennai
Data science training in Bangalore
Data science training in pune
Data science online training
Data Science Interview questions and answers
Data Science Tutorial
Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
ReplyDeleteBest Devops online Training
Online DevOps Certification Course - Gangboard
Best Devops Training institute in Chennai
It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command.
ReplyDeleterpa training in bangalore
best rpa training in bangalore
rpa training in pune | rpa course in bangalore
rpa training in chennai
This is a nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
ReplyDeleteBest Devops Training in pune
Devops Training in Bangalore
Microsoft azure training in Bangalore
Power bi training in Chennai
I have to voice my sspaion for your kindness giving support to those people that should have guidance on this important matter
ReplyDeleteWeb designing training| Web Designing in chennai | web designing
DevOps Training| devops in chennai| devops training in chennai| best training institute in chennai
Best training in Blockchain in kk nagar chennai |Check Best Training @ Chennai in KK nagar, vadapalani in chennai |Blockchain institute in Chennai | Blockchain
Check Best Software Testing Training institute in KK nagar, Chennai | Software Courses| Real time Projects
Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals.
ReplyDeleteData science Course Training in Chennai | No.1 Data Science Training in Chennai
RPA Course Training in Chennai | No.1 RPA Training in Chennai
AWS Course Training in Chennai | No.1 AWS Training in Chennai
Devops Course Training in Chennai | Best Devops Training in Chennai
Selenium Course Training in Chennai | Best Selenium Training in Chennai
Smm Panel
ReplyDeletesmm panel
iş ilanları
İnstagram Takipçi Satın Al
hirdavatci burada
beyazesyateknikservisi.com.tr
SERVİS
Tiktok Jeton Hile
ataşehir vestel klima servisi
ReplyDeleteataşehir daikin klima servisi
maltepe toshiba klima servisi
kadıköy toshiba klima servisi
maltepe beko klima servisi
kadıköy beko klima servisi
ümraniye daikin klima servisi
beykoz toshiba klima servisi
çekmeköy lg klima servisi
Good content. You write beautiful things.
ReplyDeletehacklink
taksi
mrbahis
vbet
hacklink
vbet
korsan taksi
sportsbet
sportsbet
betmatik
ReplyDeletekralbet
betpark
mobil ödeme bahis
tipobet
slot siteleri
kibris bahis siteleri
poker siteleri
bonus veren siteler
XDG751
Blogs have facilitated cross-cultural exchanges Digital Hikes enabling individuals from different countries and backgrounds to connect and share their perspectives on global topics.
ReplyDeleteKocaeli
ReplyDeleteDenizli
Bartın
Kocaeli
Adana
NPMO3
elazığ
ReplyDeletebilecik
kilis
sakarya
yozgat
5TCY
görüntülü show
ReplyDeleteücretlishow
H8U4J
ankara parça eşya taşıma
ReplyDeletetakipçi satın al
antalya rent a car
antalya rent a car
ankara parça eşya taşıma
EP7E
Tokat Lojistik
ReplyDeleteKonya Lojistik
Mersin Lojistik
Karabük Lojistik
Samsun Lojistik
LLQ7
EAD27
ReplyDeleteKonya Şehirler Arası Nakliyat
Bingöl Lojistik
Bayburt Şehir İçi Nakliyat
Bitlis Parça Eşya Taşıma
Tunceli Şehirler Arası Nakliyat
Sinop Evden Eve Nakliyat
Iğdır Lojistik
Uşak Şehirler Arası Nakliyat
Bilecik Parça Eşya Taşıma
D2713
ReplyDeleteSilivri Çatı Ustası
Eryaman Boya Ustası
Erzincan Evden Eve Nakliyat
Batman Şehirler Arası Nakliyat
Trabzon Evden Eve Nakliyat
Çankırı Şehir İçi Nakliyat
AAX Güvenilir mi
Samsun Evden Eve Nakliyat
Antep Parça Eşya Taşıma
50DDC
ReplyDeleteHamster Coin Hangi Borsada
Iğdır Şehir İçi Nakliyat
Antalya Lojistik
Mersin Şehirler Arası Nakliyat
Bursa Lojistik
Batman Lojistik
Çerkezköy Oto Boya
Çerkezköy Parke Ustası
Ağrı Parça Eşya Taşıma
5450C
ReplyDeleteorder testosterone propionat
Batman Evden Eve Nakliyat
buy sustanon
Afyon Evden Eve Nakliyat
Eskişehir Evden Eve Nakliyat
Tunceli Evden Eve Nakliyat
buy peptides
order testosterone enanthate
Diyarbakır Evden Eve Nakliyat
ACA28
ReplyDeletereferans kodu
1F908
ReplyDeleteurfa bedava sohbet odaları
samsun sesli sohbet sesli chat
ücretsiz sohbet
burdur telefonda kızlarla sohbet
hakkari sesli görüntülü sohbet
en iyi görüntülü sohbet uygulaması
bedava sohbet odaları
bayburt telefonda canlı sohbet
sohbet sitesi
35CE2
ReplyDeleteMexc Borsası Güvenilir mi
Sohbet
Sohbet
Periscope Takipçi Hilesi
Coin Üretme Siteleri
Tiktok Takipçi Satın Al
Trovo Takipçi Satın Al
Referans Kimliği Nedir
Referans Kimliği Nedir
AB8E2
ReplyDeleteYıldırım
Köse
Gölpazarı
Karlıova
Sorgun
Reyhanlı
Salıpazarı
Sultangazi
Hacılar
شركة تنظيف مجالس بالدمام xrH4Hw8W6O
ReplyDeleteشركة تسليك مجاري بالاحساء NssazQ1RiQ
ReplyDelete