next up previous contents
Next: Java datatypes Up: MPI Java Wrapper Implementation. Previous: Class methods for Java   Contents

Java native method

The Java native method is a great way to gain and merge the power of C or C++ programming into Java. To use Java as a scientific and high performance language, when efficient native Java compilers are not fully implemented, use native method can boost the performance to at least the speed of C compiled code.

Example 2. Example showing how Java native method works. :
public class JMPI {
  public native int Init(String[] args);
  public native int Finalize();
  static {

JMPI.h : (created by javah and JMPI.class)
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <native.h>
/* Header for class JMPI */

#ifndef _Included_JMPI
#define _Included_JMPI

typedef struct ClassJMPI {
    char PAD;	/* ANSI C requires structures to have a least one member
} ClassJMPI;

#ifdef __cplusplus
extern "C" {
struct Hjava_lang_String;
extern long JMPI_Init(struct HJMPI *,HArrayOfString *);
extern long JMPI_Finalize(struct HJMPI *);
#ifdef __cplusplus

JMPI.c : (created by javah -stub and JMPI.class)
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <StubPreamble.h>

/* Stubs for class JMPI */
/* SYMBOL: "JMPI/Init([Ljava/lang/String;)I", Java_JMPI_Init_stub */
stack_item *Java_JMPI_Init_stub(stack_item *_P_,struct execenv *_EE_) {
	extern long JMPI_Init(void *,void *);
	_P_[0].i = JMPI_Init(_P_[0].p,((_P_[1].p)));
	return _P_ + 1;
/* SYMBOL: "JMPI/Finalize()I", Java_JMPI_Finalize_stub */
stack_item *Java_JMPI_Finalize_stub(stack_item *_P_,struct execenv
*_EE_) {
	extern long JMPI_Finalize(void *);
	_P_[0].i = JMPI_Finalize(_P_[0].p);
	return _P_ + 1;

JMPINative.c : 
#include "mpi.h"
#include "JMPI.h"
#include "stdlib.h"

long JMPI_Init(struct HJMPI *this, HArrayOfString *args) {
  int i, result, len;
  char** sargs; 
  HString **data = unhand(args)->body;
  len = obj_length(args);
  sargs = (char**)calloc(len, sizeof(char*));
  for (i=0; i<len; i++) {
    sargs[i] = allocCString(data[i]);
  result = MPI_Init(&len, &sargs);
  for (i=0; i<len; i++) free(sargs[i]);
  return result;

long JMPI_Finalize(struct HJMPI *this) {
  return MPI_Finalize();
The only programs user created are and JMPINative.c. The JMPI.h and JMPI.c are generated by javah and compiled JMPI.class files. Compile the JMPI.c and JMPINative.c into (in UNIX) or JMPI.dll (in Microsoft Windows) and you are done.

Bryan Carpenter 2002-07-12