2016-09-27 67 views
3

我正在尝试使用gcc为Windows 7构建java本机库。 我得到它来编译和构建。面向Windows 7的Java本机库,printf

作为一个测试,我只是试图在本机代码中执行printf()

gcc -o Test.so -shared -O -I/home/fred/jdk1.8.0_65/include -I/home/fred/jdk1.8.0_65/include/linux Test.c 

在TEST.C:

JNIEXPORT void JNICALL Java_Test_print(JNIEnv *env, jobject jo) { 
    printf("Test\n"); 
} 

运行时,它不会从返回的printf()。

如果我删除printf()Java_Test_print()返回。

如果我用while(1){} 替换printf(),它会按预期挂起。

我知道它获取到我的本机代码,但它不会从printf()返回并使JVM崩溃。

在dll上的ldd显示它使用的是/usr/bin/cygwin1.dll

我怀疑调用约定有问题。即使是这样,我也不知道该怎么做。

是否有人成功开发了Windows的本地库?或者有任何指针。谢谢!

+0

你'包括stdio.h'?你有什么警告? –

回答

0
Step 1: 

    Test.c: 
    #include <jni.h> 
    #include <stdio.h> 
    #include <string.h> 
    JNIEXPORT void JNICALL Java_Test_print(JNIEnv *env, jobject jo) { 
     printf("Test\n"); 
     return; 
    } 

    Step 2: 
    Build .dll file 
    gcc -Wl,--add-stdcall-alias -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" -shared -o Test.dll Test.c 

    Step 3: 
    public class Test { 
    public native void print(); 
    static { 
     System.loadLibrary("Test"); 
     } 
    public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { 
     Test test = new Test(); 
       test.print(); 
    } 
    } 

参考链接https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html