实战-C++调用Java函数

环境

  • Windows7 64-bit
  • JDK1.7 32-bit (jdk-7u71-windows-i586.exe)
  • ADT 32-bit (adt-bundle-windows-x86-20140702.zip)
  • VS2010
  • 在环境变量PATH中添加java的路径(这样Eclipse才能启动)
  • 在环境变量PATH中添加jvm.dll所在的路径(这果才能从c++中启动jvm虚拟机)
  • 最终PATH变量如下所示
    ...;C:\Program Files (x86)\Java\jre7\bin;C:\Program Files (x86)\Java\jre7\bin\client;

编写简单的被测程序

  • 在Eclipse中建立java工程,这里笔者命名为FunCall_C2Java_Callee
  • 建立package com.uuorange.example
  • 创建类MainScene.java 如下
package com.uuorange.example;

import javax.swing.JOptionPane;

public class MainScene
{
    public static void main(String[] args)
    {
        JOptionPane.showMessageDialog(null, "MainScene.main() was called!", "Tip", JOptionPane.INFORMATION_MESSAGE);
    }

    public static void fun()
    {
        JOptionPane.showMessageDialog(null, "MainScene.fun() was called!", "Tip", JOptionPane.INFORMATION_MESSAGE);

    } 
}

  • Export可执行的jar文件,这里我导出到e:\FunCall_C2Java_Callee.jar,运行此jar文件可看到弹出提示框“MainScene.main() was called!”

编写C++测试程序

  • 在VS2010中新建Console程序,这里笔者命名为 FunCall_C2Java_Caller
  • 修改生成的FunCall_C2Java_Caller.cpp为如下内容
// FunCall_C2Java_Caller.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "jni.h"

int _tmain(int argc, _TCHAR* argv[])
{

    JavaVM *jvm;       /* denotes a Java VM */
    JNIEnv *env;       /* pointer to native method interface */
    JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */
    JavaVMOption* options = new JavaVMOption[3];
    options[0].optionString = "-Djava.compiler=NONE"; 
    options[1].optionString = "-Djava.class.path=e:/FunCall_C2Java_Callee.jar";
    options[2].optionString = "-verbose:jni";
    vm_args.version = JNI_VERSION_1_6;
    vm_args.nOptions = 3;
    vm_args.options = options;
    vm_args.ignoreUnrecognized = false;

    /* load and initialize a Java VM, return a JNI interface
     * pointer in env */
    JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
    delete options;
    /* invoke the Main.test method using the JNI */
    jclass cls = env->FindClass("com/uuorange/example/MainScene");
    jmethodID mid = env->GetStaticMethodID(cls, "fun", "()V");
    env->CallStaticVoidMethod(cls, mid, 100);
    /* We are done. */
    jvm->DestroyJavaVM();

    return 0;
}

  • 添加"jni.h"所需路径到项目的头文件搜索路径
    • 笔者路径是 “C:\Program Files (x86)\Java\jdk1.7.0_71\include” “C:\Program Files (x86)\Java\jdk1.7.0_71\include\win32"
  • 添加jvm.lib到项目依赖库列表中
  • 添加jvm.lib所在目录到链接搜索路径中
    • 笔者路径是 “C:\Program Files (x86)\Java\jdk1.7.0_71\lib”
  • 生成可执行文件

测试

执行生成的exe文件,弹出提示框“MainScene.fun() was called!”说明调用成功

参考

http://stackoverflow.com/questions/819536/how-to-call-java-function-from-chttp://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/invocation.html


代码下载:http://download.csdn.net/detail/bsxylj/8140897

你可能感兴趣的:(java,jvm,C++,jar,jni)