Friday, November 2, 2012

Call C functions from Java through JNA

Here is an example of a Java program which calls a C function through JNA (Java Native Access)

First, we implement the C program. Here is the header file "my_cprog.h"

#include <stdio.h>
#include <stdlib.h>

extern int foo(int bar);

Here is the C code for "my_cprog.c"

#include <stdio.h>
#include <stdlibh>
#include "my_cprog.h"

int foo(int bar)
    int result = 0;
    printf("\n bar = %d", bar);
    result = (bar*bar);
    return result;

int main(int argc, char **argv)

    int x = 15;
    int res = 0;

    res = foo(x);

    printf("\n X = %d, and result = %d", x, res);

    return 0;

Next, we compile the C program (in the below example, I'm doing this on MacOSX)

gcc -dynamiclib -o libmy_cprog.dylib my_cprog.c

After the "gcc" above, we get the following file


Next, we implement the Java program. I'm compiling the code on Eclipse. Here is my ""

package com.giri.jna;

import com.sun.jna.Library;
import com.sun.jna.Native;

public interface MyLibrary extends Library {
 MyLibrary INSTANCE = (MyLibrary) Native.loadLibrary("my_cprog", MyLibrary.class);
 int foo(int bar);

Here is "" which has the "main" method. One important thing to note here: We need to download "jna.jar" and add that JAR file to our eclipse project which has these 2 files.

package com.giri.jna;

import com.sun.jna.Library;

public class MainClass {
 public static void main(String[] args) {
  try {
   System.out.println("Result => " + 15));
  } catch(Exception e) {



When we run "" as a java application, here is the output.

 Result = 225
 bar = 15

No comments :

Post a Comment