posts - 0, comments - 0, trackbacks - 0, articles - 4
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

JAVA通过JNI调用C

Posted on 2007-02-13 16:52 gyb 阅读(276) 评论(0)  编辑  收藏 所属分类: JAVA JNI
package com;

public   class  JniTest {

    
/*
     * 本地方法
     
*/
    
public  native  int   get ();
    
public  native  void   set ( int  i);
    
public  native  static   int  getName();
    
public  native  static   void  setName( int  i);
    
    
public   static   void  main(String[] args) {
        System.loadLibrary(
" jnitest " );
        JniTest.setName(
1 );
        JniTest.setName(
2 );
        
        JniTest t1 
=   new  JniTest();
        t1.
set ( 11 );
        
        JniTest t2 
=   new  JniTest();
        t2.
set ( 22 );
        
        System.
out .println(JniTest.getName());
        System.
out .println(t1. get ());
        System.
out .println(t2. get ());
    }
}

用javah -jni -d "T:/c/jnitest" com.JniTest得到com_JniTest.h头文件
将下面代码的#include <jni.h>改为#include "jni.h"
/* DO NOT EDIT THIS FILE - it is machine generated */
#include 
<jni.h>
/* Header for class com_JniTest */

#ifndef _Included_com_JniTest
#define _Included_com_JniTest
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_JniTest
 * Method:    get
 * Signature: ()I
 
*/
JNIEXPORT jint JNICALL Java_com_JniTest_get
  (JNIEnv 
*, jobject);

/*
 * Class:     com_JniTest
 * Method:    set
 * Signature: (I)V
 
*/
JNIEXPORT 
void JNICALL Java_com_JniTest_set
  (JNIEnv 
*, jobject, jint);

/*
 * Class:     com_JniTest
 * Method:    getName
 * Signature: ()I
 
*/
JNIEXPORT jint JNICALL Java_com_JniTest_getName
  (JNIEnv 
*, jclass);

/*
 * Class:     com_JniTest
 * Method:    setName
 * Signature: (I)V
 
*/
JNIEXPORT 
void JNICALL Java_com_JniTest_setName
  (JNIEnv 
*, jclass, jint);

#ifdef __cplusplus
}
#endif
#endif

建立C工程:
4.JPG

在工程中加入头文件com_JniTest.h   jni_md.h   jni.h
5.JPG
创建一个新的C文件jnidll.c
#include "com_JniTest.h"

jint n 
= 0;

JNIEXPORT jint JNICALL Java_com_JniTest_get(JNIEnv 
*env, jobject obj)
{
    
return n;
}

JNIEXPORT 
void JNICALL Java_com_JniTest_set(JNIEnv *env, jobject obj, jint i)
{
    n 
= i;
}

JNIEXPORT jint JNICALL Java_com_JniTest_getName(JNIEnv 
*env, jclass cls)
{
    
return n+10;
}


JNIEXPORT 
void JNICALL Java_com_JniTest_setName(JNIEnv *env, jclass cls, jint i)
{
    n 
= i+5;
}
生成DLL文件给JAVA调用,DLL文件名为改为jnitest.dll好使得System.loadLibrary("jnitest");可以找到文件


注意:如果出现找不到方法的异常请修改jni_md.h中#define JNICALL __stdcall为:#define JNICALL然后重新编译DLL