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。

原文地址:https://www.cnblogs.com/rocky-fang/p/6016327.html