Easy to code Java with C/C++

Easy to code Java with C/C++

  1. Generate file header for class in Java (use to include in C/C++)
  2. Include file header in project C/C++ in Visual studio and write code => create .DLL file
  3. Call .DLL file in Java code
1. Generate file header for class in Java
(I using Netbeans)
Write class in java with some "native" methods. Class MyNative with two methods Sum and Sub

Open cmd and redirect to source folder ..projectname/src
run: javah javaandccplus.MyNative

After run it, we have a file header javaandccplus_MyNative.h with code 

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class javaandccplus_MyNative */

#ifndef _Included_javaandccplus_MyNative
#define _Included_javaandccplus_MyNative
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     javaandccplus_MyNative
 * Method:    Sum
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_javaandccplus_MyNative_Sum
  (JNIEnv *, jobject, jint, jint);

/*
 * Class:     javaandccplus_MyNative
 * Method:    Sub
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_javaandccplus_MyNative_Sub
  (JNIEnv *, jobject, jint, jint);

#ifdef __cplusplus
}
#endif
#endif

2. Include file header in project C/C++ in Visual studio
Create a console application with VS 2012. Select App type is DLL in App setting.

Copy file header (.h) and past into project C/C++ folder. Then add this header into project
Create a .cpp file to include this header.

Config project C/C++ to include JNI header.
ProjectName -> properties -> C/C++ -> generate -> Additional Include Directories

Implement code to two methods Sum and Sub

#include "stdafx.h"
#include "javaandccplus_MyNative.h"

JNIEXPORT jint JNICALL Java_javaandccplus_MyNative_Sum
  (JNIEnv *, jobject, jint ja, jint jb)
{
jint sum = ja  + jb;
return sum;
}

JNIEXPORT jint JNICALL Java_javaandccplus_MyNative_Sub
  (JNIEnv *, jobject, jint ja, jint jb)
{
return ja - jb;
}

Build project we have a .dll file like ProjectWithHeaderFromJava.dll in folder debug
3. Call .DLL file in Java code
Ceate folder in project folder and copy .DLL into this folder. JavaAndCCplus/libs/ProjectWithHeaderFromJava.dll
Add library path: JavaAndCCplus -> properties -> run VM options
and add -Djava.library.path="libs"
Create a class to call methods in this DLL file.
package javaandccplus;

public class CallDLL {
    public static void main(String[] args)
    {
        System.loadLibrary("ProjectWithHeaderFromJava");
        MyNative nt = new MyNative();
        System.out.println("Sum 3 + 4 = " + nt.Sum(3, 4));
        System.out.println("Sub 3 - 4 = " + nt.Sub(3, 4));
        
    }
}



Run and enjoy.
P/s: this way can apply for android using native code with JNI

Feel free to contact me.

Comments

Popular posts from this blog

Recognize text from image with Python + OpenCV + OCR

Install OpenCV to work with Python

Edit image with Android and OpenCV and JNI (C/C++)