JNI不识别jni原始类型,例如串

时间:2016-04-25 17:21:57

标签: java c types java-native-interface

我已经为C标头创建了一个make文件,但是这很好但是说JNICALLJNIEnv存在语法错误,但我发现它是因为类型在头文件中。

Image of the failure

图片中的代码在这里:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class GameLogic */

#ifndef _Included_GameLogic
#define _Included_GameLogic
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     GameLogic
 * Method:    hello
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_GameLogic_hello
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

当我尝试运行项目时,我收到错误:

Exception in thread "main" java.lang.UnsatisfiedLinkError: GameLogic.hello()Ljava/lang/String;
    at GameLogic.hello(Native Method)
    at GameLogic.<init>(GameLogic.java:7)
    at GameLogic.main(GameLogic.java:11)

C档案:

#import <jni.h>
#import <stdio.h>
#include "GameLogic.h"

JNIEXPORT jstring JNICALL Java_GameLogic_hello (JNIEnv * env, jobject thisObj) {
    return (*env)->NewStringUTF(env, "Sup");
}

通用生成文件:

# Define a variable for classpath
CLASS_PATH = ../

# Define a virtual path for .class in the bin directory
vpath %.class $(CLASS_PATH)

all : libGameLogic.jnilib

# $@ matches the target, $< matches the first dependancy
libGameLogic.jnilib : GameLogic.o
    gcc -dynamiclib -framework JavaVM -o $@ $<

# $@ matches the target, $< matches the first dependancy
GameLogic.o : GameLogic.c GameLogic.h
    gcc -I/System/Library/Frameworks/JavaVM.framework/Headers -framework JavaVM -c $< -o $@

# $* matches the target filename without the extension
GameLogic.h : GameLogic.class
    javah -classpath $(CLASS_PATH) $*

clean :
    rm GameLogic.h GameLogic.o libGameLogic.jnilib

GameLogic:

public class GameLogic {

    public native String hello ();

    public GameLogic  () {
        System.out.println(hello());
    }

    public static void main (String[] args) {
        new GameLogic ();
    }

}

2 个答案:

答案 0 :(得分:1)

尝试使用以下方式进行编译:

gcc -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/darwin/" -dynamiclib -o libGameLogic.jnilib GameLogic.c

然后在您的类文件中,您需要添加:

static {
    // GameLogic.dll (Windows) or libGameLogic.so (Unixes) or libGameLogic.jnilib (Mac)
    System.loadLibrary("GameLogic");
}

最后你启动你的课程 (假设你的文件.class和你的lib libGameLogic.jnilib在当前目录中)

java -Djava.library.path=. GameLogic

答案 1 :(得分:0)

所以我弄清楚问题是什么。我忘了说图书馆在哪里。

static {
        System.load(System.getProperty("user.dir")+"/jni/libhello.jnilib");
    }

然后,日食所带来的所有错误实际上并不存在,只能被忽略。谢谢大家。