I recently started coding in Java and have been trying to use the native methods to link code from other languages like C and C++.
My code for the file is:
public class NativeDemo {
int i;
public static void main(String args[]) {
NativeDemo ob = new NativeDemo();
ob.i = 10;
System.out.println("This is ob.i before the native method:" +
ob.i);
ob.test(); // call a native method
System.out.println("This is ob.i after the native method:" +
ob.i);
}
// declare native method
public native void test() ;
// load DLL that contains static method
static {
System.loadLibrary("NativeDemo");
}
}
I compiled the file to produce the .class file and then with the following command :
javah -jni NativeDemo
have been able to produce the header file NativeDemo.h
Next I coded the .c file:
/* This file contains the C version of the
test() method.
*/
#include <jni.h>
#include "NativeDemo.h"
#include <stdio.h>
JNIEXPORT void JNICALL Java_NativeDemo_test(JNIEnv *env, jobject obj)
{
jclass cls;
jfieldID fid;
jint i;
printf("Starting the native method.\n");
cls = (*env)->GetObjectClass(env, obj);
fid = (*env)->GetFieldID(env, cls, "i", "I");
if(fid == 0) {
printf("Could not get field id.\n");
return;
}
i = (*env)->GetIntField(env, obj, fid);
printf("i = %d\n", i);
(*env)->SetIntField(env, obj, fid, 2*i);
printf("Ending the native method.\n");
}
But now when I try to use this command:
Cl/LD NativeDemo.c
the response I get is:
'Cl' is not recognized as an internal or external command,
operable program or batch file.
How should I proceed after this, and where exactly can I link my .c file with me Java code?