• java jni c++ 例子


    1. java程序

    public class TestHello {
    
        static {
    
            System.loadLibrary("TestHello");
    
        }
    
        
        public static native int add(int a, int b);
    
        public static void main(String[] args) {
    
            int c = add(2, 5);
            System.out.print("result:::::"+c);
    
        }
    
    }

    2 编译

      javac TestHello.java

    3. 生成c++头文件

     javah TestHello

    4. 创建 DLL动态链接库工程 TestHello

      visual studio 2010:  File->new->project->win32 project-> dll->TestHello

    5. 引入 jni.h, jni_md.h TestHello.h

      TestHello工程右键-> Properties->Configuration Properties->C/C++ ->General -> Additional Include Directories

    6. 在TestHello.cpp中 实现TestHello.h中的函数

    // TestHello.cpp : Defines the exported functions for the DLL application.
    //
    
    #include "stdafx.h"
    #include "dllApi.h"
    
    
    JNIEXPORT jint JNICALL Java_TestHello_add
        (JNIEnv * env, jclass obj, jint a, jint b){
        int var =0;
        dllApi* test = new dllApi();
        var = test->DLL_API_ADD(a, b);
        delete test;
        return  var;
    };

    dllApi.h

    #pragma once
    class dllApi
    {
    public:
        dllApi(void);
        ~dllApi(void);
    
        int DLL_API_ADD(int , int );
    
        int DLL_API_SUB(int , int );
    
        int DLL_API_MUL(int , int );
    
        int DLL_API_DIV(int , int );
        
    };

    dllApi.cpp

    #include "StdAfx.h"
    #include "dllApi.h"
    
    
    dllApi::dllApi(void)
    {
    }
    
    
    dllApi::~dllApi(void)
    {
    }
    
    int dllApi :: DLL_API_ADD(int a, int b){
        return (a + b);
    };
    
    int dllApi :: DLL_API_SUB(int a, int b){
        return (a-b);
    };
    
    int dllApi :: DLL_API_MUL(int a, int b){
        return (a*b);
    };
    
    int dllApi ::  DLL_API_DIV(int a, int b){
        return (a/b);
    };

    7. 编译生成TestHello.dll

    8. 将dll文件拷贝到class目录下, 执行class文件,OK。

  • 相关阅读:
    Java正则表达式入门1
    JAVA中正则表达式总结
    Java正则表达式入门
    java String.valueOf()的作用
    【HDOJ】3601 Coach Yehr’s punishment
    【HDOJ】4601 Letter Tree
    【HDOJ】3686 Traffic Real Time Query System
    【HDOJ】5296 Annoying problem
    【HDOJ】3553 Just a String
    【HDOJ】4426 Palindromic Substring
  • 原文地址:https://www.cnblogs.com/rocky-fang/p/6016327.html
Copyright © 2020-2023  润新知