tags:

views:

54

answers:

0

In one of my Java projects I am expected to call a C function. As I am new to JNI, I first attempted a simple Helloworld program.

I wrote a class with a reference to a native method by name sayHello() which returns void and takes no argument. I compiled the class and generated the header file using the javah utility. I then copied over the signature of this function into a new C file as a new function and just called printf("Hello, World!") in that function. I generated a dll from it using gcc on my cygwin shell. I verified that the dll contained the function. I registered the dll using the regsvr32 utility.

When I ran the java program to call the sayHello() function, the dll is getting loaded, which I verified by trying to delete the dll when this program was still running, but there is no response and the application seems to be waiting for something.

What could be the problem with this?

The source code is as follows:

/* Hello.java */
public class Hello
{
    static
    {
     System.loadLibrary("hello");
    }

    public native void sayHello();

    public static void main(String[] args)
    {
     Hello h = new Hello();
     h.sayHello();
    }
}


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

#ifndef _Included_Hello
#define _Included_Hello
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     Hello
 * Method:    sayHello
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_Hello_sayHello
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif


/* Hello.c */
#include <stdio.h>
#include <jni.h>

#include "Hello.h"

JNIEXPORT void JNICALL Java_Hello_sayHello
  (JNIEnv *env, jobject obj)
{
    printf("Hello, World!");
    return;
}