简体   繁体   English

在C ++中有条件地调用JNI

[英]Conditionally call JNI in C++

I have C++ code that needs to run on two different environments - one with Java installed, one without. 我有C ++代码,需要在两种不同的环境上运行-一种安装了Java,一种没有安装。 In the Java environment, it will need to make JNI calls. 在Java环境中,它将需要进行JNI调用。

My current setup is as follows: 我当前的设置如下:

Main.cpp: Main.cpp的:

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

JNIInterface.h: JNIInterface.h:

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

JNIInterface.cpp: 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". 如预期的那样,在非Java环境中,它会导致“由于您的计算机缺少JVM.dll,导致程序无法启动”。

It seems like the only way is to avoid including the JNI code at compile time in the preprocessor. 似乎唯一的方法是避免在编译时在预处理器中包含JNI代码。 Is there a different setup to avoid this issue? 是否有其他设置可以避免此问题?

Since you mention "DLL" I'll assume Windows. 由于您提到“ DLL”,因此我假设使用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. 这样可以防止在启动时(但仅在首次调用时)加载DLL。 No call, no load, no problem if the DLL is missing. 没有调用,没有负载,如果DLL丢失,也没有问题。 Just a setting in MSVC. 只是MSVC中的设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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