Native Methods in Java

Discussion in 'Java' started by obscurecoder, Jun 28, 2010.

  1. obscurecoder

    obscurecoder New Member

    Jun 7, 2010
    Likes Received:
    Trophy Points:
    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.test(); // call a native method
    System.out.println("This is ob.i after the native method:" +
    // declare native method
    public native void test() ;
    // load DLL that contains static method
    static {
    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");
    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?
    Last edited by a moderator: Jun 28, 2010

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice