java调用c++

文章描述了如何通过JNI接口,让Java代码调用C++编写的函数,具体步骤包括生成JNI头文件,编写C++代码,使用Mingw64编译成dll动态库,然后在Java中加载并执行该dll,从而实现跨语言的函数调用。
摘要由CSDN通过智能技术生成

1.声明c++ 所需要的native方法供java调用

 

  1. javac Hello.java -h . 

生成 c++ 的头文件

 

test_Hello.h 内容为

/* DO NOT EDIT THIS FILE - it is machine generated */

#include <jni.h>

/* Header for class test_Hello */

#ifndef _Included_test_Hello

#define _Included_test_Hello

#ifdef __cplusplus

extern "C" {

#endif

/*

 * Class:     test_Hello

 * Method:    helloFromCPP

 * Signature: ()V

 */

JNIEXPORT void JNICALL Java_test_Hello_helloFromCPP

  (JNIEnv *, jobject);

#ifdef __cplusplus

}

#endif

#endif

  1. 编写c++ 代码

复制 test_Hello.h 后缀改为cpp 内容为

/* DO NOT EDIT THIS FILE - it is machine generated */

#include <jni.h>

#include <stdio.h>

#include "test_Hello.h"

JNIEXPORT void JNICALL Java_test_Hello_helloFromCPP

  (JNIEnv *, jobject){

printf("%s","i am from c++");

  

}

方法参数不能修改,只能修改函数体

  1. 使用 gcc 编译生成 hello.dll

下载

 

Mingw64 ,在该目录下cmd 命令行执行, 其中 -I参数为引入java框架 本地的c++ 头文件  -share 位输出 一个dll , 最后的参数为 cpp 实际的代码文件

gcc -I "D:\Program Files\Java\jdk1.8.0_201\include" -I "D:\Program Files\Java\jdk1.8.0_201\include\win32" -shared -o hello.dll  D:\workspace\参考框架\test1\src\main\java\test\test_Hello.cpp

  1. 将生成好 hello.dll 放到java 工程的根路径

 

运行java代码

package org.example;

import test.Hello;

// MyJavaClass.java

public class TestCallDll {

    public static void main(String[] args) {

        Hello a = new Hello();

        a.helloFromCPP();

    }

}

package test;

public class Hello {

    public native void helloFromCPP();

    static{

        System.out.println(System.getProperty("user.dir"));

        System.load(System.getProperty("user.dir") + "\\hello.dll");

    }

}

输出 c++ 的内容

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值