Calling Java Methods from Visual C/C++ using C++/CLI

空扰寡人 提交于 2019-12-23 03:29:41

问题


I'm getting a "error LNK1104: cannot open file {path}\jvm.lib" when trying tocompile a VS C++/CLI (managed) project. It's very simple and my goal is to call some Java methods in pre-existing java libs - here is the code I'm using:

// This is the main DLL file.

#include "stdafx.h"
#include <jni_md.h>
#include <jni.h>
#include "JBridge.h"

#pragma once

using namespace System;

namespace JBridge 
{

public ref class JniBridge
{
    // TODO: Add your methods for this class here.


public:
    void HelloWorldTest()
    {
        System::Console::WriteLine("Hello Worldl from managed C++!");
    }

    JNIEnv* create_vm(JavaVM ** jvm) 
    {
        JNIEnv *env;
        JavaVMInitArgs vm_args;

        JavaVMOption options; 
        //Path to the java source code     
        options.optionString = "-Djava.class.path=D:\\Java Src\\TestStruct"; 
        vm_args.version = JNI_VERSION_1_6; //JDK version. This indicates version 1.6
        vm_args.nOptions = 1;
        vm_args.options = &options;
        vm_args.ignoreUnrecognized = 0;

        int ret = JNI_CreateJavaVM(jvm, (void**)&env, &vm_args);
        if(ret < 0)
            printf("\nUnable to Launch JVM\n");       
        return env;
    }
    };
}

I've verified the file does exist in the path location and I've added it to the project properties for the include dir and the linker property pages.

Update Got the jvm.lib to be linked with a bit more fiddling.

Compilation causes following errors during build:

Error 1 error LNK2028: unresolved token (0A00000A) "extern "C" long __stdcall JNI_CreateJavaVM(struct JavaVM_ * *,void * *,void *)" (?JNI_CreateJavaVM@@$$J212YGJPAPAUJavaVM_@@PAPAXPAX@Z) referenced in function "struct JNIEnv_ * __cdecl create_vm(struct JavaVM_ * *)" (?create_vm@@$$FYAPAUJNIEnv_@@PAPAUJavaVM_@@@Z) c:\Temp\CLRTest\JBridge\JBridge\JBridge.obj JBridge Error 2 error LNK2019: unresolved external symbol "extern "C" long __stdcall JNI_CreateJavaVM(struct JavaVM_ * *,void * *,void *)" (?JNI_CreateJavaVM@@$$J212YGJPAPAUJavaVM_@@PAPAXPAX@Z) referenced in function "struct JNIEnv_ * __cdecl create_vm(struct JavaVM_ * *)" (?create_vm@@$$FYAPAUJNIEnv_@@PAPAUJavaVM_@@@Z) c:\Temp\CLRTest\JBridge\JBridge\JBridge.obj JBridge Error 3 error LNK1120: 2 unresolved externals c:\temp\CLRTest\JBridge\Debug\JBridge.dll JBridge


回答1:


Work around was to dynamically load the JVM by using LoadLibrary("path/to/jvm"); and then invoking the native functions.



来源:https://stackoverflow.com/questions/9999913/calling-java-methods-from-visual-c-c-using-c-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!