// CCode with documentation and conditional compilation. Code with a "j" in // the first column is specific to being called from Java, code with a "c" in // the first column is specific for stand alone C code not called by Java, and // code with a blank first column is common to both being called from Java and // stand alone. Note that in the functional code the "j" and "c" entries in // the first column must be removed and all the #define, #include etc. // directives have to start in the first column. #define JAVA 1 // This flag is set when the code is called from Java. #include <stdio.h> // FORTRAN routines have to be prototyped as extern, and parameters are // passed by reference. Note also that for g77 the function name in C by // default must be prefixed by a "_". extern int sumsquaredf_(int *, int []); #ifdef JAVA // The block of code below is compiled when called from Java. j j #include "JavaCode.h" // Required header for JNI j j // When calling C code from Java, main() must be replaced by a declaration j // similar to below, where the function name is given by "Java_" + the name j // of the class in the Java code that calls this C code, in this case j // "JavaCode", + "_" + the name of this C function called from Java, in this j // case "sumsquaredc". This is followed by at least two parameters as below, j // plus possibly more if more are required. j j JNIEXPORT jint JNICALL Java_JavaCode_sumsquaredc(JNIEnv *env, j jobject obj, jintArray ja) { j j // Data from any additional parameters are passed via special pointers as j // shown here. j j jsize n = (*env)->GetArrayLength(env, ja); j jint *a = (*env)->GetIntArrayElements(env, ja, 0); j int i,result; j #else // The block of code below is compiled when Java is not used. c c #define LEN 10 c int main() { c int i,n,result,a[LEN]; c n = LEN; // Do some initializations when Java is not used. c for (i=0; i<n; i++) c a[i]=i; c #endif // The block of code below is common to C and Java. printf("-- We are now in the C program CCode --\n"); printf("Print contents of array a[] copied from arr[] in Java\n"); for (i=0; i<n; i++) printf("%2d %5d\n",i,a[i]); printf("Call the FORTRAN code\n"); // The data are passed to the FORTRAN program, then the results are returned // in a way similar to this. result = sumsquaredf_(&n,a); printf("-- We have now returned back to the C program --\n"); printf("Print contents of array a[]\n"); for (i=0; i<n; i++) printf("%2d %5d\n",i,a[i]); printf("Sum of squares in array = %d\n",result); #ifdef JAVA // This section of code is compiled when called from Java. j j // Instead of ending as a normal C program, the pointers must be cleared j // before returning to Java. j j (*env)->ReleaseIntArrayElements(env, ja, a, 0); j return result; j #else // Otherwise we just end as a normal C program c c return; c #endif }