home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Programming Languages Suite
/
ProgLangD.iso
/
VCAFE.3.0A
/
Sample.bin
/
jni2.cpp
< prev
next >
Wrap
C/C++ Source or Header
|
1998-02-26
|
3KB
|
125 lines
/*
* jni2.cpp
*
* This cpp code will create a Java VM
* and call Hello.printHello().
*
* Note that this code can either
* be linked with an import library if
* STATIC is defined, or load a DLL
* during run-time.
*/
#include <windows.h>
#include <jni.h>
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
void main()
{
JNIEnv *env;
JavaVM *jvm;
JDK1_1InitArgs vm_args;
jclass cls;
jmethodID mid;
vm_args.version = 0x00010001;
#if STATIC // link statically with import lib snjjni.lib or javai.lib
// init vm_args and create Java VM
JNI_GetDefaultJavaVMInitArgs( &vm_args );
vm_args.classpath = getenv( "CLASSPATH" );
if( JNI_CreateJavaVM( &jvm, &env, &vm_args ) < 0 )
{
cout << "error: cannot create Java VM" << endl;
exit( 1 );
}
#else // link dynamically to runtime (preferred)
#if BYTECODE // use bytecode runtime
char * dllname = "javai.dll";
#else // use native runtime
char * dllname = "snjrt11.dll";
#endif
// load the DLL containing Java VM
HMODULE hm = LoadLibrary( dllname );
if( hm == 0 )
{
cout << "error: cannot load " << dllname << endl;
exit( 1 );
}
// get a handle to JNI_GetDefaultJavaVMInitArgs() and init vm_args
jint (JNICALL *f1ptr)( void * );
f1ptr = (jint (JNICALL *)( void * )) GetProcAddress( hm, "JNI_GetDefaultJavaVMInitArgs" );
if( f1ptr == 0 )
{
cout << "error: cannot get JNI_GetDefaultJavaVMInitArgs() address " << endl;
exit( 1 );
}
(*f1ptr)( &vm_args );
vm_args.classpath = getenv( "CLASSPATH" );
// get a handle to JNI_CreateJavaVM() and create Java VM
jint (JNICALL *f2ptr)( JavaVM **, JNIEnv **, void * );
f2ptr = (jint (JNICALL *)( JavaVM **, JNIEnv **, void * )) GetProcAddress( hm, "JNI_CreateJavaVM" );
if( f2ptr == 0 )
{
cout << "error: cannot get JNI_CreateJavaVM() address " << endl;
exit( 1 );
}
if( (*f2ptr)( &jvm, &env, &vm_args ) < 0 )
{
cout << "error: cannot create Java VM" << endl;
exit( 1 );
}
#endif
if( env == 0 )
{
cout << "error: JNIenv null pointer" << endl;
exit( 1 );
}
// look for samples.jni2.Hello6 class
cls = env->FindClass( "samples/jni2/Hello6" );
if( cls == 0 )
{
cout << "error: cannot find class samples.jni2.Hello6" << endl;
exit(1);
}
// get static method Hello6.printHello()
mid = env->GetStaticMethodID( cls, "printHello", "()V" );
if( mid == 0 )
{
cout << "error: cannot find samples.jni2.Hello6.printHello()" << endl;
exit( 1 );
}
// invoke Hello6.printHello()
env->CallStaticVoidMethod( cls, mid );
// destroy Java VM
jvm->DestroyJavaVM();
}