Monday, December 15, 2014

An Introduction to JNI using a Bottom Up Approach: Step 3

Continued from An Introduction to JNI using a Bottom Up Approach: Step 2. Note: These steps may be followed without the first step below, if you remove the two references to CPPHelper in the C code and remove "CPPHelper.cpp" from the commands to compile and run "CToCPPHelper.exe".

Step 3: C Main Function

  1. Comment out the main function in "CPPHelper.cpp".
    /*  Uncomment to compile and run CPPHelper.exe  
    int main()
    {
     cout << "CPP_HELPER MAIN START" << endl;
     cppHelperEntryPoint();
     cout << "CPP_HELPER MAIN FINISH" << endl;
    }
    */
  2. In your working directory, add an empty file, named "CToCPPHelper.h"
  3. In your working directory, add the following code, in a file named "CToCPPHelper.cpp":
    #include "CToCPPHelper.h"
    #include "CPPHelper.h" // Comment to ignore CPPHelper
    #include <jni.h>
    #include <stdio.h>

    void cToCPPHelperExitPoint() {
        printf("C_TO_CPP_HELPER EXIT START\n");
        cppHelperEntryPoint(); // Comment to ignore CPPHelper
        printf("C_TO_CPP_HELPER EXIT FINISH\n");
    }

    int main()
    {
        printf("C_TO_CPP_HELPER MAIN START\n");
        cToCPPHelperExitPoint();
        printf("C_TO_CPP_HELPER MAIN FINISH\n");
    }

    JNIEXPORT void JNICALL Java_com_mycompany_myapp_JavaToCHelper_cToCPPHelperEntryPoint(JNIEnv *env, jobject thisObj)
    {
        printf("C_TO_CPP_HELPER ENTRY START\n");
        cToCPPHelperExitPoint(); // Comment to ignore CPPEntryPoint
        printf("C_TO_CPP_HELPER ENTRY FINISH\n");
    }
  4. Compile the code and run "CToCPPHelper.exe", using the following commands:
    cd /D "C:\Users\Scott\workspace\myrepo\my-app\src\main\resources\dlls"

    "C:\MinGW64\bin\g++.exe" -I"C:\Program Files\Java\jdk1.6.0_26\include" -I"C:\Program Files\Java\jdk1.6.0_26\include\win32" -o CToCPPHelper.exe CToCPPHelper.c CPPHelper.cpp PrintOpenWindows.cpp

    CToCPPHelper.exe
Continued at An Introduction to JNI using a Bottom Up Approach: Step 4.

This post was reposted from http://scottizu.wordpress.com/2013/08/21/an-introduction-to-jni-using-a-bottom-up-approach-step-3/, originally written on August 21st, 2013.

1 comment:

  1. The file should be "CToCPPHelper.c" since this is a C file and not a C++ file. Also, the JDK might be different so you may have to check your file system or install Java. For example, instead of Java 6 Update 26 "jdk1.6.0_26" you might have Java 7 Update 51 "jdk1.7.0_51".

    ReplyDelete