Calling existing C functions with JNI

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sampalmer21
    New Member
    • Feb 2008
    • 11

    #1

    Calling existing C functions with JNI

    I have a dll containing c functions which I cannot edit in any way. How do I call those functions using JNI without having to add the java generated header files/functions into the c file?
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by sampalmer21
    I have a dll containing c functions which I cannot edit in any way. How do I call those functions using JNI without having to add the java generated header files/functions into the c file?
    You never have to add anything to existing code. Let foo.h be the header file of
    your existing code, containing:

    [code=c]
    #ifndef FOO_H
    #define FOO_H
    extern int foo();
    #endif
    [/code]

    Generate a Java class like this:

    [code=java]
    public class FooWrapper {
    static { // load the library
    System.loadLibr ary("FooWrapper .dll");
    }
    native int fooWrapper();
    }
    [/code]

    compile it and make the FooWrapper.h header file using the javah tool and the
    compiled .class file. Next create your wrapper method:

    [code=c]
    #include <foo.h> /* the real function declaration */
    #include <FooWrapper.h > /* the generated wrapper declaration */

    /* definition of the wrapper */
    jint fooWrapper( ...) {

    /* your code here calling foo()
    }
    [/code]

    Now compile your FooWrapper.c file, link your compiled c file to a .dll and voila.

    kind regards,

    Jos
    Last edited by JosAH; Apr 11 '08, 11:42 AM. Reason: corrected the compilation order

    Comment

    Working...