无法编译 JNI C 不兼容的指针类型



我正在编写一些本机代码,以将RPI sense hat与我的java内容进行接口,但我无法让我的本机代码隐含。我用java编写了存根,对其进行了编译,然后使用javah提取了一个头文件。我在C中创建了一些方法,将一个简单的char数组转换为一个用于返回的字符串。我似乎无法编译它。Java:

/**
 * NativeTest - PACKAGE_NAME
 * Created by matthew on 21/07/16.
 */
class SenseHat
{
    static {
        System.loadLibrary("SenseHat");
    }
    public native String getTemperature();
    public native String getHumidity();
    public native String getOrientation();
}

头文件:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class SenseHat */
#ifndef _Included_SenseHat
#define _Included_SenseHat
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     SenseHat
 * Method:    getTemperature
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_SenseHat_getTemperature
  (JNIEnv *, jobject);
/*
 * Class:     SenseHat
 * Method:    getHumidity
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_SenseHat_getHumidity
  (JNIEnv *, jobject);
/*
 * Class:     SenseHat
 * Method:    getOrientation
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_SenseHat_getOrientation
  (JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif

C文件:

#include <jni.h>
#include <stdio.h>
#include "SenseHat.h"
JNIEXPORT jstring JNICALL Java_SenseHat_getTemperature(JNIEnv *env, jobject thisObj) {
   char done[] = "temperature";
   jstring answer;
   /* Make a new String based on done, then free done. */
   answer = (*env)->NewStringUTF(env,&done);
   free(done);
   return answer;
}
JNIEXPORT jstring JNICALL Java_SenseHat_getHumidity(JNIEnv *env, jobject thisObj) {
   char done[9] = "humidity";
   jstring answer;
   /* Make a new String based on done, then free done. */
   answer = (*env)->NewStringUTF(env,&done);
   free(done);
   return answer;
}
JNIEXPORT jstring JNICALL Java_SenseHat_getOrientation(JNIEnv *env, jobject thisObj) {
   char done[12] = "orientation";
   jstring answer;
   /* Make a new String based on done, then free done. */
   answer = (*env)->NewStringUTF(env,&done);
   free(done);
   return answer;
}

我使用以下命令编译它:

gcc -I /usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/include/ -I /usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/include/linux/ -shared -o libSenseHat.so SenseHat.c

你不能做

   char done[] = "temperature";
   /* ... */
   answer = (*env)->NewStringUTF(env,&done);
                                /* --^-- & is redundant */

应该是

   char done[] = "temperature";
   /* ... */
   answer = (*env)->NewStringUTF(env,done);

甚至

   answer = (*env)->NewStringUTF(env,"temperature");

你也不应该free(done)。此内存未使用malloc()分配,因此释放会导致未定义的行为。

我看到的第一个问题是:声明局部数组变量并对它们使用free()。使用malloc()/free()或在本地声明数组,但不要将两者混合使用。

最新更新