Jace 一种方便的 JNI机制

本文介绍多种从C++程序中调用Java方法的技术方案,包括使用JNI、Jace等工具,以及通过命令行方式启动Java应用。特别提供了一个使用JNI调用Java静态方法的具体示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

为了实现 C++ 调用 Java的函数,以下方法可供参考。https://www.xingdaili.com/browse.php?u=RDFxE%2Bw3stMHuV6Q%2BLJWhbnh4Fb4JxGnYdxt1UkqyGFlfDtFncjT9tbFhUZUE6%2BW26h1OWzBt06FC4GH6pS4VY6iXDkrt6DXpPJosrmDOfQVVzgDl7rvjPaA6LZFYMTgWo73wlSBrNr4G7M%3D&b=6

Use JNI
Use Jace
Use JunC++ion
Use execl("java", "java", "-jar", "myprog.jar", NULL);
Use execlp("java", "java", "-jar", "myprog.jar", (char *)0);
Use system("java filename.jar");
Use popen("java -jar test.jar text1 text2", "r");
Use CreateProcess(...);
Use JNA

I'm trying to call / execute a java jar from a C++ program.

Here are the options I've found so far:

Use JNI
Use Jace
Use JunC++ion
Use execl("java", "java", "-jar", "myprog.jar", NULL);
Use execlp("java", "java", "-jar", "myprog.jar", (char *)0);
Use system("java filename.jar");
Use popen("java -jar test.jar text1 text2", "r");
Use CreateProcess(...);
Use JNA

I'd like to use JNI, however I'm running into problems.

========================

Hello.cpp

I have a simple Hello.cpp class:

#include <iostream>
#include <jni.h>

using namespace std;

int main() {
      cout << "Hello World" << endl; // prints Hello World

      JavaVM *jvm;       /* denotes a Java VM */
      JNIEnv *env;       /* pointer to native method interface */
      JDK1_1InitArgs vm_args; /* JDK 1.1 VM initialization arguments */
      vm_args.version = 0x00010001; /* New in 1.1.2: VM version */
      /* Get the default initialization arguments and set the class
       * path */
      JNI_GetDefaultJavaVMInitArgs(&vm_args);
      vm_args.classpath = "/home/FinishedJars/HelloWorld/hello2.jar";
      /* load and initialize a Java VM, return a JNI interface
       * pointer in env */
      JNI_CreateJavaVM(&jvm, &env, &vm_args);
      /* invoke the Main.test method using the JNI */
      jclass cls = env->FindClass("Main");
      jmethodID mid = env->GetStaticMethodID(cls, "test", "(I)V");
      env->CallStaticVoidMethod(cls, mid, 100);
      /* We could have created an Object and called methods on it instead */
      /* We are done. */
      jvm->DestroyJavaVM();

    return 0;
}

========================

Compile

And when I try to compile with something like:

g++ -I /usr/lib/jvm/jdk1.6.0_34-x86/include/ Hello.cpp

Note: I found "jni.h" in that folder, so I included it. I'm assuming that's the right spot, but I'm not certain

I get a ton of errors ( see below )

转载于:https://www.cnblogs.com/cy163/archive/2013/05/14/3078807.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值