使用Windows服务使用JNI和LoadLibrary调用java程序的问题

时间:2011-11-01 09:11:39

标签: java c windows service java-native-interface

我正在创建一个调用java程序的Windows服务程序。

以下是代码的一部分,hModule是一个全局变量,在ServiceStart中调用LoadLibrary,然后调用invokeJVM。我设法启动服务并且运行正常,但是,每当我停止服务时,它都会给我一个错误: Windows无法在本地计算机上停止该服务 错误1067:Windows服务意外终止

添加额外的日志记录后,我发现发生意外终止错误的地方是invokeJVM函数的返回。 当我检查事件查看器时,它给了我一些BEX错误,在谷歌上搜索,说它是一个堆栈溢出错误,但我无法确定它的原因,任何想法为什么?

HMODULE hModule;

VOID ServiceStart ( DWORD dwArgc, LPTSTR *lpszArgv )
{
    // Let the service control manager know that the service is
    // initializing.
    if ( !ReportStatus( SERVICE_START_PENDING, NO_ERROR, 3000 ) )
        //goto cleanup;
        return;

    hModule = LoadLibrary( TEXT( "C:\\Program Files (x86)\\Java\\jre6\\bin\\client\\jvm.dll" ) );

    // Create a Stop Event
    if ( !( hServerStopEvent = CreateEvent( NULL, TRUE, FALSE, NULL) ) )
        goto cleanup;

    lpszJavaArgs = getJavaArgs( &lpszJavaArgs, &dwJLen, dwArgc, lpszArgv );
    lpszAppArgs = getAppArgs( &lpszAppArgs, &dwALen, dwArgc, lpszArgv );
    wrkdir = getWorkingDirectory( dwArgc, lpszArgv );

    if ( !ReportStatus( SERVICE_RUNNING, NO_ERROR, 0 ) )
        goto cleanup;

    // After the initialization is complete (we've checked for arguments) and
    // the service control manager has been told the service is running, invoke
    // the Java application. If clients are unable to access 
    // the server, check the event log for messages that should indicate any errors
    // that may have occured while firing up Java...

    invokeJVM( NULL );

    // Wait for the stop event to be signalled.
    WaitForSingleObject( hServerStopEvent, INFINITE );

cleanup:
    ( VOID ) ReportStatus( SERVICE_STOPPED, 0, 0 );
    if ( hServerStopEvent )
        CloseHandle( hServerStopEvent );
    ( *vm ) -> DestroyJavaVM( vm );
    FreeLibraryAndExitThread( hModule, 0 );

    return;
}

VOID invokeJVM( VOID *dummy )
{
    jint res;
    jclass cls;
    jmethodID mid;
    jstring jstr;
    jobjectArray args;
    JavaVMInitArgs vm_args;
    JavaVMOption options[ MAX_OPTIONS ];
    jint ( *createJavaVM )( JavaVM **, void **, void * ) = 
        ( jint ( * )( JavaVM **, void **, void * ) ) GetProcAddress( hModule, "JNI_CreateJavaVM" );
    char buf[256];
    jclass cls2;
    jmethodID mid2;
    UINT uIdx;

    if ( wrkdir )
    {
        if ( !SetCurrentDirectory( wrkdir ) )
            AddToMessageLog( TEXT( "Unable to change working directory." ) );
    }

    if(dwJLen > MAX_OPTIONS)
    {
        AddToMessageLog( TEXT( "Max. number of Java args exceeded." ) );
        return;
    }

    // Assign the arguments for the JVM, such as the classpath,
    // RMI codebase, etc.
    for ( uIdx = 0; uIdx < dwJLen; ++uIdx )
        options[ uIdx ].optionString = lpszJavaArgs[ uIdx ]; // PROBLEM HERE

    vm_args.version = JNI_VERSION_1_6;
    vm_args.options = options;
    vm_args.nOptions = dwJLen;
    vm_args.ignoreUnrecognized = TRUE;

    //res = JNI_CreateJavaVM( &vm, ( void ** ) &env, &vm_args );
    res = ( *createJavaVM )( &vm, ( void ** ) &env, &vm_args );
    if ( res < 0 )
    {
        AddToMessageLog( TEXT( "Cannot create Java VM." ) );
        return;
    }

    // Get the main class
    if ( !( cls = ( *env ) -> FindClass( env, SZMAINCLASS ) ) )
    {
        AddToMessageLog( TEXT( "Cannot find main class." ) );
        return;
    }

    // Get the method ID for the class's main(String[]) function. 
    if ( !( mid = ( *env ) -> GetStaticMethodID( env, cls, "main", "([Ljava/lang/String;)V" ) ) )
    {
        AddToMessageLog( TEXT( "Cannot find main method." ) );
        return;
    }

    // If there are arguments, create an ObjectArray sized to contain the
    // argument list, and then scan the list, inserting each argument into
    // the ObjectArray.
    if( dwALen > 0 )
    {
        if ( !( args = ( *env ) -> NewObjectArray( env, dwALen, ( *env ) -> FindClass( env, "java/lang/String" ), NULL ) ) ) 
        {
            AddToMessageLog( TEXT( "Out of Memory!" ) );
            return;
        }

        for( uIdx = 0; uIdx < dwALen; ++uIdx )
        {
            if ( !( jstr = ( *env ) -> NewStringUTF( env, lpszAppArgs[ uIdx ] ) ) )
            {
                AddToMessageLog( TEXT( "Out of Memory!" ) );
                return;
            }
            ( *env ) -> SetObjectArrayElement( env, args, uIdx, jstr );
        }
    }
    // Otherwise, create an empty array. This is needed to avoid
    // creating an overloaded main that takes no arguments in the Java
    // app, and then getting a different method ID to the no-argument
    // main() method in this invoker code.
    else
    {
        args = ( *env ) -> NewObjectArray( env, 0, ( *env ) -> FindClass( env, "java/lang/String" ), NULL );
    }

    //Now, get the class of the java SCMEventManager
    if ( !( cls2 = ( *env ) -> FindClass( env, SZSCMEVENTMANAGER ) ) )
    {
        AddToMessageLog( TEXT( "Cannot find SCMEventManager class." ) );
        goto finished;
    }

    //Get the method ID for SCMEventManager.getInstance()
    sprintf( buf, "()L%s;", SZSCMEVENTMANAGER );
    if ( !( mid2 = ( *env ) -> GetStaticMethodID( env, cls2, "getInstance", buf ) ) )
    {
        AddToMessageLog( TEXT( "Cannot find SCMEventManager.getInstance." ) );
        goto finished;
    }

    //Call SCMEventManager.getInstance() and save the returned object
    //We'll use this later on.

    if ( !( jobj = ( *env ) -> NewGlobalRef( env, ( *env ) -> CallStaticObjectMethod( env, cls2, mid2 ) ) ) )
    {
        AddToMessageLog( TEXT( "Cannot call SCMEventManager.getInstance." ) );
        goto finished;
    }

finished:
    // Run the main class...
    ( *env ) -> CallStaticVoidMethod( env, cls, mid, args );
    SetConsoleCtrlHandler( logoffHandler, TRUE );

    return;
}

1 个答案:

答案 0 :(得分:2)

您可能使用了错误的调用约定。如果您尝试这样的事情会发生什么:

jint (__stdcall *createJavaVM )( JavaVM **, void **, void * ) = ( jint ( __stdcall * )( JavaVM **, void **, void * ) ) GetProcAddress( hModule, "JNI_CreateJavaVM" );

P.S。 如果不是stdcall,请找出它是哪一个。