我有一个自己的构建 Eclipse 插件,我需要在其中调用 C++ dll。
我尝试分两步执行此操作: 1. 在我的 Eclipse 插件之外通过调用 C++ dll 的 Java 主程序 2. 尝试将其放入我的插件中(这就是问题所在)
- Eclipse 插件之外。
主要 Java 代码 HelloWorld.java。
class HelloWorld {
//public native void print(); //native method
public native String print(String msg); //native method
static //static initializer code
{
System.loadLibrary("CLibHelloWorld");
}
public static void main(String[] args)
{
//HelloWorld hw = new HelloWorld();
//hw.print();
String result = new HelloWorld().print("Hello from Java");
System.out.println("In Java, the returned string is: " + result);
}
}
通过命令编译:“C:\Program Files\Java\jdk1.6.0_34\bin\javac”HelloWorld.java
然后我通过以下方式为 C++ dll 制作了一个 h 文件 HelloWorld.h:
"C:\Program Files\Java\jdk1.6.0_34\bin\javah" HelloWorld
h 文件如下所示:
#include <jni.h>
/* Header for class HelloWorld */
#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: HelloWorld
* Method: print
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_HelloWorld_print
(JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif
现在是 C++ dll CLibHelloWorld.cpp :
#include "HelloWorld.h"
#include "jni.h"
#include "stdafx.h"
#include "tchar.h"
#import "..\ManagedVBDLL\bin\Debug\ManagedVBDLL.tlb" raw_interfaces_only
using namespace ManagedVBDLL;
JNIEXPORT jstring JNICALL Java_HelloWorld_print(JNIEnv *env, jobject thisObj, jstring inJNIStr) {
jboolean blnIsCopy;
const char *inCStr;
char outCStr [128] = "string from C++";
inCStr = env->GetStringUTFChars(inJNIStr, &blnIsCopy);
if (NULL == inCStr) return NULL;
printf("In C, the received string is: %s\n", inCStr);
env->ReleaseStringUTFChars(inJNIStr, inCStr);
return env->NewStringUTF(outCStr);
}
构建 dll
当我运行 java 主程序时……一切正常!
- 尝试将它放入我的 Eclipse 插件中(这就是问题所在)
我做了一个应该调用 C++ dll 的类:
package org.eclipse.ui.examples.recipeeditor.support;
import org.eclipse.jface.dialogs.MessageDialog;
public class HelloWorld {
public native String print(String msg); //native method
static //static initializer code
{
try {
System.loadLibrary("CLibHelloWorld"); //$NON-NLS-1$
} catch (Exception e) {
e.printStackTrace();
MessageDialog.openInformation(null, "HelloWorld", "HelloWorld Catch: " + e.getMessage());
}
}
}
并这样称呼它:
HelloWorld hw = new HelloWorld();
result = hw.print("Hi from Eclipse");
然后我在 hw.print 上得到这个错误(dll 的加载完成):
java.lang.UnsatisfiedLinkError: org.eclipse.ui.examples.recipeeditor.support.HelloWorld.print(Ljava/lang/String;)Ljava/lang/String;
一个很长的故事,但我该如何解决呢?
谢谢。