2009年12月4日星期五

jni with c++

what i do here is:
from a c++ built exe(1) create a jvm and load a java made jar(2),
in java, use jni to call a c++ build dll(3).
so we need 3 program, 2 in c++ and 1 in java.

i use visual studio 2008 express and eclipse. i just show some code here.

------------------
// jbwloader.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include
#include


int _tmain(int argc, _TCHAR* argv[]){
JNIEnv *env;
JavaVM *jvm;
jint res;
jclass cls;
jmethodID mid;
jstring jstr;
jclass stringClass;
jobjectArray args;

JavaVMInitArgs vm_args;
JavaVMOption options[2];
options[0].optionString =
"-Djava.class.path=c:\\long\\jbw.jar";
options[1].optionString =
"-Djava.library.path=c:\\long";
vm_args.version = 0x00010002;
vm_args.options = options;
vm_args.nOptions = 2;
vm_args.ignoreUnrecognized = JNI_TRUE;
/* Create the Java VM */
res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);

if (res < cls =" env">FindClass("neoe/jbw/Main");
if (cls == 0) {
goto destroy;
}

mid = env->GetStaticMethodID( cls, "main",
"([Ljava/lang/String;)V");
if (mid == 0) {
goto destroy;
}
jstr = env->NewStringUTF( " from C++!");
if (jstr == 0) {
goto destroy;
}
stringClass = env->FindClass( "java/lang/String");
args = env->NewObjectArray( 1, stringClass, jstr);
if (args == 0) {
goto destroy;
}
env->CallStaticVoidMethod( cls, mid, args);

destroy:
if (env->ExceptionOccurred()) {
env->ExceptionDescribe();
}
jvm->DestroyJavaVM();
return 0;
}


----------------
package neoe.jbw;

import java.io.FileWriter;
import java.util.Date;

public class Main {

/**
* @param args
*/
public static void main(String[] args) {
try {
System.out.println("s1");
System.loadLibrary("cmodule");
System.out.println("s2");
new Main().run();
} catch (Throwable e) {
e.printStackTrace();
}

}

private void run() throws Exception {
FileWriter out =new FileWriter("t:/jbw.txt");
out.write("i am here "+new Date());
out.close();
cprint1();
}
public native void cprint1();
}



---------------
// This is the main DLL file.

#include "stdafx.h"

#include "cmodule.h"

#include
#include

extern "C"
JNIEXPORT void JNICALL
Java_neoe_jbw_Main_cprint1(JNIEnv *env, jobject obj)
{
printf("print from c++!\n");
return;
}


command line:
> jbwloader.exe
s1
s2
print from c++!

also, important but strange, you should add jre/bin/client which contains jvm.dll into your env value PATH

if you cannot see some #include, it is because the html tag. you can view html source of this page to see what they are.

没有评论:

博客归档

neoedmund's shared items

我的简介

ZIP Code File