JNI演示HelloWorld

时间:2016-09-12 15:30:22

标签: java c java-native-interface

这是我的第一个JNI demo.My os是win7,我的ide是IDEA。

创建Java文件HelloWorld

HelloWold.java:

public class HelloWorld {
        public static native void sayHello();

        public static void main(String[] args) {
           new HelloWorld().sayHello();
        }

        static {
            System.load("D:\\JavaJNIDemo\\jni\\helloworld.dll");
        }

}

Javah生成.h文件

com_uniquestudio_coxier_HelloWorld.h:

#include <jni.h>
#ifndef _Included_com_uniquestudio_coxier_HelloWorld
#define _Included_com_uniquestudio_coxier_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_uniquestudio_coxier_HelloWorld
 * Method:    sayHello
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_com_uniquestudio_coxier_HelloWorld_sayHello
  (JNIEnv *, jclass);

#ifdef __cplusplus
}
#endif
#endif

新建一个c档

HelloWorld.c:

#include <jni.h>
#include <stdio.h>
#include "com_uniquestudio_coxier_HelloWorld.h"


JNIEXPORT void JNICALL Java_com_uniquestudio_coxier_HelloWorld_sayHello
  (JNIEnv *env, jclass object){
   printf("Hello World!\n");
   return;
  }

在我的win7上生成dll

我遇到了一个问题:

  

未知类型名称&#34; __ int64&#34;在jni_md.h

我通过this

解决了这个问题

然后我用:

D:\JavaJNIDemo\jni>gcc -Wl,--add-stdcall-alias -I"%JAVA_HOME%\include" -I"%JAVA_
HOME%\include\win32" -shared -o helloworld.dll HelloWorld.c

错误

当我运行程序时,我收到此错误: 错误:

A fatal error has been detected by the Java Runtime Environment:

EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0000000180105979, pid=6776, tid=7040

JRE version: Java(TM) SE Runtime Environment (8.0_20-b26) (build 1.8.0_20-b26)
Java VM: Java HotSpot(TM) 64-Bit Server VM (25.20-b23 mixed mode windows-amd64 compressed oops)
Problematic frame:
C  [cygwin1.dll+0xc5979]

Failed to write core dump. Minidumps are not enabled by default on client versions of Windows

An error report file with more information is saved as:
D:\JavaJNIDemo\hs_err_pid6776.log

1 个答案:

答案 0 :(得分:0)

我将编译器更改为MinGW64。然后它可以正常工作