简体   繁体   中英

Conditionally call JNI in C++

I have C++ code that needs to run on two different environments - one with Java installed, one without. In the Java environment, it will need to make JNI calls.

My current setup is as follows:

Main.cpp:

#include "JNIInterface.h"
if(useJNI){
    JNIInterface::DoJNIStuff();
} else {
    DoNormalStuff();
}

JNIInterface.h:

#include <mutex>
//has no <jni.h> include
...

JNIInterface.cpp:

#include "JNIInterface.h"
#include <jni.h>
void JNIInterface::DoJNIStuff()
{   std::call_once(jvmFlag, [](){
        //basically all the JVM initialization stuff    
    });
    DoStuff(jvm);
}

As expected, on the non-Java environment it results in "The program can't start because JVM.dll is missing from your computer".

It seems like the only way is to avoid including the JNI code at compile time in the preprocessor. Is there a different setup to avoid this issue?

Since you mention "DLL" I'll assume Windows. The simple solution is something called delay-loading. This prevents a DLL from being loaded at startup, but only when it's first called. No call, no load, no problem if the DLL is missing. Just a setting in MSVC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM