JNI 无法识别 jni 原始类型,例如细绳

JNI not recognising jni primitive types e.g. string

我已经为 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

游戏逻辑:

public class GameLogic {

    public native String hello ();

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

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

}

尝试编译使用:

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

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

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

最后,您将 class 作为下一个 启动(假设您的文件 .class 和您的库 libGameLogic.jnilib在当前目录):

java -Djava.library.path=. GameLogic

所以我已经弄清楚问题出在哪里了。我忘了说图书馆在哪里。

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

然后 eclipse 启动的所有错误实际上并不存在,可以忽略。谢谢大家