一个简单的JNI示例

JNI C Linux平台:一个简单的示例程序 以下是一个在Linux平台上使用JNI(Java Native Interface)和C语言编写的简单示例程序。这个简单的示例演示了如何在Linux平台上使用JNI和C语言进行函数调用和数据传递。您可以根据自己的需求扩展和修改这个示例,以实现更复杂的功能。接下来,我们需要使用Javah工具生成C头文件。然后,我们需要编写一个简单的Makefile来编译C代码并生成共享库。首先,我们需要编写一个Java类来加载C本地库并调用C函数。,我们将在C代码中实现该方法。头文件以获取JNI函数的声明,并包含了生成的。 阅读详情
Java Native Interface(JNI)是Java语言的本地编程接口,是J2SDK的一部分。在java程序中,我们可以通过JNI实现一些用java语言不便实现的功能。通常有以下几种情况我们需要使用JNI来实现。
  • 标准的java类库没有提供你的应用程序所需要的功能,通常这些功能是平台相关的
  • 你希望使用一些已经有的类库或者应用程序,而他们并非用java语言编写的
  • 程序的某些部分对速度要求比较苛刻,你选择用汇编或者c语言来实现并在java语言中调用他们

在《java核心技术》中,作者提到JNI的时候,建议不到万不得已不要使用JNI技术,一方面它需要你掌握更多的知识才可以驾驭,一方面使用了JNI你的程序就会丧失可移植性。

下面我们开始编写HelloWorld程序,由于涉及到要编写c/c++代码因此我们会在开发中使用Microsoft VC++工具。

  1. 编写java代码
    我们在硬盘上建立一个hello目录作为我们的工作目录,首先我们需要编写自己的java代码,在java代码中我们会声明native方法,代码非常简单。如下所示
    class HelloWorld
    {
        public native void displayHelloWorld();
        static {
            System.loadLibrary("hello");
        }
       
        public static void main(String[] args) {
            new HelloWorld().displayHelloWorld();
        }
    }
    注意我们的displayHelloWorld()方法的声明,它有一个关键字native,表明这个方法使用java以外的语言实现。方法不包括实现,因为我们要用c/c++语言实现它。注意System.loadLibrary("hello")这句代码,它是在静态初始化块中定义的,系统用来装载hello共享库,这就是我们在后面生成的hello.dll(如果在其他的操作系统可能是其他的形式,比如hello.so)
  2. 编译java代码
    javac HelloWorld.java  生成HelloWorld.class文件
  3. 创建.h文件
    这一步中我们要使用javah命令生成.h文件,这个文件要在后面的c/c++代码中用到,我们运行
    javah HelloWorld。这样我们可以看到在相同目录下生成了一个HelloWorld.h文件,文件内容如下
    在此我们不对他进行太多的解释。
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class HelloWorld */
    #ifndef _Included_HelloWorld
    #define _Included_HelloWorld
    #ifdef __cplusplus
    extern "C" {
    #endif
    /*
     * Class:     HelloWorld
     * Method:    displayHelloWorld
     * Signature: ()V
     */
    JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld
      (JNIEnv *, jobject);
    #ifdef __cplusplus
    }
    #endif
    #endif
  4. 编写本地实现代码
    在这部分我们要用C/C++语言实现java中定义的方法,我们在VC++中新建一个Project,然后创建一个HelloWorldImp.cpp文件,内容如下
    #include <jni.h>
    #include "HelloWorld.h"
    #include <stdio.h>

    JNIEXPORT void JNICALL
    Java_HelloWorld_displayHelloWorld(JNIEnv *env, jobject obj)
    {
        printf("Hello world!/n");
        return;
    }
    注意我们这里include了 jni.h和刚才得到的HelloWorld.h文件。因此你要在VC++里面设置好,jni.h在JAVA_HOME/include里面。编译通过后再生成hello.dll文件。
  5. 运行java程序
    把上面生成的hello.dll文件复制到我们的工作目录,这时候我们的目录中包括HelloWorld.java,HelloWorld.class和hello.dll文件。运行java HelloWorld命令,则可在控制台看到Hello world|
    的输出了。
    JNI是一门复杂,有趣且富有挑战性的技术,我们在后面的几篇文章中将说明如何在java语言和Native语言之间进行交互。


DexProtector内存态匿名段检测绕过与dex重组技术 Dex文件是Android应用的核心执行单元,其结构规范(如header_item、class_def_item、code_item)决定了运行时加载与解析的底层逻辑。DexProtector通过将dex数据拆解为多个无文件名、受保护的内存匿名段(如[anon:dp_header]、[anon:dp_code]),规避传统基于文件特征或标准加载路径的检测机制。该策略依赖Android mmap内存管理与ART虚拟机对dex结构的刚性要求,形成可被观测的布局规律。理解其内存态组织原理,结合权限/大小/命名/内 阅读详情

相关推荐

Python xlwings报错解决:从‘NoneType‘到完美运行WPS表格的完整指南

本文深入解析了使用Python xlwings库自动化WPS表格时遇到的经典'NoneType'报错(AttributeError: 'NoneType' object has no attribute 'apps')的根源与解决方案。核心在于pywin32版本与WPS的兼容性问题,文章提供了从版本降级、依赖管理到构建健壮自动化环境的完整实战指南,帮助开发者彻底解决兼容性难题,实现稳定运行。

n4o5p6q7r的博客 303

Android JNI基础篇(一)

JNI学习其实并不难,在这里,我将引导大家学习JNI的基础知识,认真学完本教程,你将更加坚信我说的话。来吧,我们一起学习!

kgdwbb的专栏 2万+

Mann-Kendall检验全解析:从原理到11种变体及Python实现

本文全面解析Mann-Kendall检验,从基础原理到应对自相关、季节性等复杂数据的11种关键变体,如Hamed-Rao修正、季节性MK和趋势自由预白化(TFPW)。详细阐述各方法的适用场景与数学原理,并提供完整的Python实战代码,帮助研究者针对不同数据特性选择最稳健的趋势分析方法。

weixin_29050271的博客 457

Android NDK开发:JNI基础篇

Android NDK开发:JNI基础篇 JNI 概念 1.1 概念JNI 全称 Java Native Interface,Java 本地化接口,可以通过 JNI 调用系统提供的 API。操作系统,无论是 Linux,Windows 还是 Mac OS,或者一些汇编语言写的底层硬件驱动都是 C/C++ 写的。Java和C/C++不同 ,它不会直接编译成平台机器码,而是编译成虚拟机可以运行的Java

cfanr 2138

PyCharm + Anaconda虚拟环境:完美配置PySide6开发三件套(Designer/UIC/RCC)的避坑指南

本文详细介绍了如何在PyCharm和Anaconda虚拟环境中配置PySide6开发三件套(Designer/UIC/RCC),提供从环境准备到工具集成的完整解决方案。通过清晰的路径定位和PyCharm外部工具配置指南,帮助开发者快速搭建高效的Python GUI开发环境,避免常见配置陷阱。

weixin_28828243的博客 338

HDLBits答案汇总

前言 该博客为本人做HDLBits习题时的心得记录总结,欢迎大家一起交流进步。 HDLBits网站链接 Verilog Language Basics Vectors Modules:Hierarchy Procedures More Verilog Features Circuits Combinational Logic Basic gates Multiplexers Arithmetic Circuits Karnaugh Map to Circuit Sequential Logic Latche

谦豫 9万+

JNI简单示例

JNI简单示例

fdyufgf的博客 1278

博途 V15.1安装步骤

温馨提醒:安装此软件电脑配置至少应满足以下要求 处理器 CoreTM i5-3320M 3.3 GHz 或相当 内存 至少8G 硬盘 300 GB SSD 显示器 15.6' 宽屏显示 (1920 x 1080) 1.双击打开【Siemens v15.1】文件夹。 2.鼠标右击【STEP 7 BasicProfess...

谢谢关注“小鱼教你模数电”,各平台同号 9万+

android JNI 的简单示例

这段时间接触到JNI的东西,网上虽然有很多写的不错的例子,还是写下自己的历程。 我的环境是:XP\android开发环境。 1:下载安装Cygwin. Cygwin is: a collection of tools which provide a Linux look and feel environment for Windows. a DLL (cygwin1.dll) whi

wangxiaohong123的专栏 659

基于STM32设计的万能红外遥控器(学习型)

当前介绍了一种基于STM32微控制器设计的红外遥控器,支持接收解码功能和发送功能,可以将接收的码原样发送出去。 红外遥控器作为智能设备控制方式之一,在一定程度上满足了人们对于快速方便控制的需求。 当前设计的红外遥控器支持学习模式和发送模式。通过矩阵键盘上的数字键选择发送对应的控制码。 一共支持学习10个控制码,对应矩阵键盘上的数字。0~9。

6559

ABB机器人刷功能选项全一篇就够——不怕丢失程序和IO配置数据

ABB机器人刷功能选项

m0_66701835的博客 1259

JNI 简单示例

JNI即Java Native Interface(Java本地接口),是一个协议,主要作用为:实现Java调用c/c++代码(类库),或者C/C++调用Java代码。本文主要介绍通过JNI实现java调用C/C++ 通过Java jni来调用native code,需要如下几个步骤: 编写java代码,使用native关键字声明本地方法接口(例如:native void printstr(S...

赶路人儿 1336

图数据库Neo4j面试内容整理-Neo4j的性能

在执行复杂关系查询时,Neo4j 通过图结构的高效存储和查询机制,能够比传统的关系型数据库提供更快的性能,尤其是在涉及深层关系的查询时。通过合理的配置、优化查询和使用合适的硬件,Neo4j 可以处理大规模的数据集和高并发的查询请求,满足企业级应用的需求。Neo4j 在处理图数据时,通过优化图的存储、查询和遍历等方面,提供了高效的性能,特别适合用于需要处理复杂关系和多层次连接的应用场景,如社交网络、推荐系统、知识图谱等。:Neo4j 会根据查询的结构和数据的分布自动选择最优的查询计划。

不务正业的猿 586

[Java] [ Android ] [ JNI ] [ JNI简单示例及参数类型 ]

1、Java代码的编写 1)、首先准备一个具有本地方法的Java文件HelloJNI ,编译生成HelloJNI.class, 代码内容如下: package com.lhy.comm; public class HelloJNI { static{ //加载生成的HelloJNI2.dll System.loadLibrary(&quot;HelloJNI2&quot;...

Hendy_Raw的博客 268

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

JNI接口简单示例

JNI是Java native interface的简写,可以译作Java原生接口。Java可以通过JNI调用C/C++的库,这对于那些对性能要求比较高的Java程序无疑是一个福音。 下面我就用JNI实现一个经典的“Hello World”程序。该程序在Java中通过JNI调用c函数实现“Hello World”的输出。创建该程序分为以下步骤: 1、创建一个Java程序(HelloWorld.ja...

Android/Linux驱动开发传帮带学习,让驱动入门门槛更低! 5139

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

逆向工程 --- Android JNI,从一个简单示例开始

通过比较两个反编译器,还是ghidra厉害,ida错误多且可读性差,但是ghidra有一个重大错误,返回值是空。还是建议使用ghidra的反编译功能。而且ghidra支持多个指令集的反编译,ida只支持x86。安卓支持很多不同cpu框架上运行,但是随着不断的发展淘汰了mips和arm32位,目前arm64位和x86成为了主流支持cpu。通过分析指令集ret,发现没有正确读取w0的值,属于软件缺陷。之后的分析在不说明的情况下默认是ghidra。我们分析一下错误如何产生的。对arm64的二进制分析。

cnzzs的博客 1011

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

一个JNI的简单示例

在JAVA开发中,常常听到JNI这个名词,那么JNI究竟是什么呢? JNI,全称JAVA Native Interface,它提供若干API使得JAVA可以和C/C++语言通信。简单的说,也就是C/C++和JAVA能够相互调用。流程如下: 1.新建java测试类,名为JNITest.java,内容如下: class JNITest{ //在加载此类时先加载libhello_JNI...

weixin_40776947的博客 535
上一篇: WIN7下VS2008编译程序时的UAC控制
下一篇: @Override jdk版本不一致引发的问题
xt_chaoji
博客等级 码龄20年 86粉丝 132原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值