Calling Java Methods

解决Can‘t obtain static method fromNative(Method, Object) from class com.sun.jna.Native问题 文章目录crash日志信息解决方案参考 crash日志信息 07-06 15:31:24.866 26421 26446 E AndroidRuntime: java.lang.UnsatisfiedLinkError: Can't obtain static method fromNative(Method, Object) from class com.sun.jna.Native 07-06 15:31:24.866 26421 26446 E AndroidRuntime: at com.sun. 阅读详情

Calling Java Methods

This section illustrates how you can call Java methods from native methods. Our example program, Callbacks.java, invokes a native method. The native method then makes a call back to a Java method. To make things a little more interesting, the Java method again (recursively) calls the native method. This process continues until the recursion is five levels deep, at which time the Java method returns without making any more calls to the native method. To help you see this, the Java method and the native method print a sequence of tracing information.

Calling a Java Method from Native Code
Let us focus on the implementation of  Callbacks_nativeMethod, implemented in  Callbacks.c. This native method contains a call back to the Java method Callbacks.callback.
JNIEXPORT void JNICALL
Java_Callbacks_nativeMethod(JNIEnv *env, jobject obj, jint depth)
{
  jclass cls = (*env)->GetObjectClass(env, obj);
  jmethodID mid = (*env)->GetMethodID(env, cls, "callback", "(I)V");
  if (mid == 0)
    return;
  printf("In C, depth = %d, about to enter Java\n", depth);
  (*env)->CallVoidMethod(env, obj, mid, depth);
  printf("In C, depth = %d, back from Java\n", depth);
}
You can call an instance (non-static) method by following these three steps:
  • Your native method calls GetObjectClass. This returns the Java class object to which the Java object belongs.
  • Your native method then calls GetMethodID. This performs a lookup for the Java method in a given class. The lookup is based on the name of the method as well as the method signature. If the method does not exist, GetMethodID returns 0. An immediate return from the native method at that point causes a NoSuchMethodError to be thrown in Java code.
  • Lastly, your native method calls CallVoidMethod. This invokes an instance method that has void return type. You pass the object, method ID, and the actual arguments to CallVoidMethod.
Forming the Method Name and Method Signature

The JNI performs a symbolic lookup based on the method's name and type signature. This ensures that the same native method will work even after new methods have been added to the corresponding Java class.

The method name is the Java method name in UTF-8 form. Specify the method name for a constructor of a class by enclosing the word init within angle brackets (this appears as "<init>").

Note that the JNI uses method signatures to denote the type of Java methods. The signature (I)V, for example, denotes a Java method that takes one argument of type int and has return type void. The general form of a method signature argument is:

"(argument-types)return-type"

The following table summarizes the encoding for the Java type signatures:

Java VM Type Signatures
SignatureJava Type
Zboolean
Bbyte
Cchar
Sshort
Iint
Jlong
Ffloat
Ddouble
L fully-qualified-class ;fully-qualified-class
[ typetype[]
( arg-types ) ret-typemethod type

For example, the Prompt.getLine method has the signature:

(Ljava/lang/String;)Ljava/lang/String;
whereas the  Callbacks.main method has the signature:
([Ljava/lang/String;)V

Array types are indicated by a leading square bracket ([) followed by the type of the array elements.

Using javap to Generate Method Signatures

To eliminate the mistakes in deriving method signatures by hand, you can use the javap tool to print out method signatures. For example, by running:

javap -s -p Prompt
you can obtain the following output:
Compiled from Prompt.java
class Prompt extends java.lang.Object 
    /* ACC_SUPER bit set */
{
    private native getLine (Ljava/lang/String;)Ljava/lang/String;
    public static main ([Ljava/lang/String;)V
    <init> ()V
    static <clinit> ()V
}

The "-s" flag informs javap to output signatures rather than normal Java types. The "-p" flag causes private members to be included.

Calling Java Methods Using Method IDs

In JNI, you pass the method ID to the actual method invocation function. This makes it possible to first obtain the method ID, which is a relatively expensive operation, and then use the method ID many times at later points to invoke the same method.

It is important to keep in mind that a method ID is valid only as long as the class from which it is derived is not unloaded. Once the class is unloaded, the method ID becomes invalid. So if you want to cache the method ID, make sure to keep a live reference to the Java class from which the method ID is derived. As long as the reference to the Java class (the jclass value) exists, the native code keeps a live reference to the class. The section Local and Global References explains how to keep a live reference even after the native method returns and the jclass value goes out of scope.

Passing Arguments to Java Methods

The JNI provides several ways to pass arguments to a Java method. Most often, you pass the arguments following the method ID. There are also two variations of method invocation functions that take arguments in an alternative format. For example, the CallVoidMethodV function receives the arguments in a va_list, and the CallVoidMethodA function expects the arguments in an array of jvalue union types:

typedef union jvalue {
    jboolean z;
    jbyte    b;
    jchar    c;
    jshort   s;
    jint     i;
    jlong    j;
    jfloat   f;
    jdouble  d;
    jobject  l;
} jvalue;

Besides CallVoidMethod function, the JNI also supports instance method invocation functions with other return types, such as CallBooleanMethod,CallIntMethod, and so on. The return type of the method invocation function must match with the Java method you wish to invoke.

Calling Static Methods
You can call static Java method from your native code by following these steps:
  • Obtain the method ID using GetStaticMethodID, as opposed to GetMethodID.
  • Pass the class, method ID, and arguments to the family of static method invocation functions: CallStaticVoidMethod, CallStaticBooleanMethod, and so on.
If you compare instance method invocation functions to static method invocation functions, you will notice that instance method invocation functions receive the  object, rather than the class, as the second argument following the JNIEnv argument. For example, if we add a static method
   static int incDepth(int depth) {return depth + 1};
into  Callback.java, we can call it from  Java_Callback_nativeMethod using:
JNIEXPORT void JNICALL
Java_Callbacks_nativeMethod(JNIEnv *env, jobject obj, jint depth)
{
  jclass cls = (*env)->GetObjectClass(env, obj);
  jmethodID mid = (*env)->GetStaticMethodID(env, cls, "incDepth", "(I)I");
  if (mid == 0)
    return;
  depth = (*env)->CallStaticIntMethod(env, cls, mid, depth);
Calling Instance Methods of a Superclass
You can call instance methods defined in a superclass that have been overridden in the class to which the object belongs. The JNI provides a set of  CallNonvirtual<type>Method functions for this purpose. To call instance methods from the superclass that defined them, you do the following:
  • Obtain the method ID from the superclass using GetMethodID, as opposed to GetStaticMethodID).
  • Pass the object, superclass, method Id, and arguments to the family of nonvirtual invocation functions: CallNonvirtualVoidMethod,CallNonvirtualBooleanMethod, and so on.
It is rare that you will need to invoke the instance methods of a superclass. This facility is similar to calling a superclass method, say  f, using:
super.f();
in Java.
模拟量传输4-20ma电流 大家可能会非常熟悉RS232,RS485,CAN等工业上常用的总线,他们都是传输数字信号的方式。那么,我们用什么方式来传输模拟信号呢?工业上普遍需要测量各类非电物理量,例如温度、压力、速度、角度等,这些都需要转换成模拟量电信号才能传输到几百米外的控制室或显示设备上。工业上最广泛采用的是用4~20mA电流来传输模拟量。 采用电流信号的原因是不容易受干扰,因为工业现场的噪声电压的幅度可能达到数V,但是噪声的功率很弱,所以噪声电流通常小于nA级别,因此给4-20mA传输带来的误差非常小;电流源内阻趋于无穷. 阅读详情

相关推荐

避坑指南:在Ubuntu 22.04上配置UR5e与ROS2 Humble真机通信的完整流程

本文详细介绍了在Ubuntu 22.04上配置UR5e机械臂与ROS2 Humble真机通信的完整流程,包括环境准备、网络配置、URCap安装、ROS2驱动部署及控制器状态验证等关键步骤。特别针对常见问题如网络连接失败、驱动启动错误等提供了实用解决方案,帮助工程师高效完成UR5e与ROS2的集成工作。

weixin_30790841的博客 470

JNI开发C调用Java的方法和构造函数(三)

C调用Java的方法和构造函数

believeinbelieve的博客 1830

模拟滤波器的基础知识和设计

使用Python实现多种模拟滤波器

faltas的博客 3539

java反射之Method的invoke方法实现

在框架中经常会会用到method.invoke()方法,用来执行某个的对象的目标方法。以前写代码用到反射时,总是获取先获取Method,然后传入对应的Class实例对象执行方法。然而前段时间研究invoke方法时,发现invoke方法居然包含多态的特性,这是以前没有考虑过的一个问题。那么Method.invoke()方法的执行过程是怎么实现的?它的多态又是如何实现的呢? 本文将从java和JVM...

wenyuan65的博客 22万+

HITS算法详解及代码实现

占坑

蓁蓁尔的博客 7469

2025数学建模美赛C题完整建模思路——奥运会奖牌榜的模型

2025数学建模美赛C题完整建模思路——奥运会奖牌榜的模型

Yilu264的博客 1万+

java readtoend_Call Java method from .Net

I've to call a java method from a C# .Net concole application.The solution at the following linkProcess myProcess = new Process();Process.StartInfo.UseShellExecute = false;myProcess.StartInfo.FileName...

weixin_26757939的博客 106

【微电网优化】基于粒子群求解CHP机组、气网、电网、储热罐和电锅炉微电网优化模型附matlab代码

1 简介 我国风力发电近年发展迅速,装机容量已成为全球首位.随着风力发电在电力系统中的渗透率不断提高,我国多个地区(尤其是"三北"地区)已经面临着十分严峻的风电消纳问题,产生不容忽视的弃风问题.针对目前我国风电消纳存在的困难,本文提出粒子群优化CHP机组、气网、电网、储热罐和电锅炉微电网控制策略. 2 部分代码 Ppv=[0;0;0;0;0;0;9.86000000000000;19.0100000000000;33.1000000000000;45.0700000000000;64.7900000

qq_59747472的博客 678

JNI之------C调用java接口

主要是分调用java中的static函数和非static函数。   本地activity code: public class TestJNIActivity extends Activity { private static final String TAG = "TestJNIActivity"; static{ System.loadLibrary("shift_jni"...

私房菜 5470

2025B卷最新华为OD机试持续收录中 - 真题题库清单,按考点划分(Python / JS / C++ / JAVA / C语言)

2025B卷最新华为OD机试持续收录中 - 真题题库清单,按考点划分(Python / JS / C++ / JAVA / C语言)

算法大师! 3063

【nnUNetv2进阶】四、nnUNetv2 魔改网络-小试牛刀-加入注意力机制ChannelAttention

本文介绍了在nnunet中加入ChannelAttention的方法,按照本文教的教程,可以快速完成ChannelAttention的加入和自定义模型的跑通。

AI爱好者的博客,分享计算机领域相关知识 5812

Calling Java Class Methods from C with JNI

http://hildstrom.com/projects/jni/index.html Calling Java Class Methods from C with JNI It never fails. There is some great piece of code that will save you tons of time, but it is written i

VMLINUZ的专栏 562

【NIPS 2022】时序精选论文07|Non-stationary Transformers: 引入非平稳性信息的平稳化序列预测模型(代码解读附源码)

整体代码框架基本上与传统 Transformer 类似,基本上只有在内嵌的注意力机制模块有区别,因此这里只对关键部分进行讲解,代码整体框架可参考 Transformer。非平稳时序很难预测,尤其对模型泛化性影响很大,试想下推理阶段的数据分布变了,模型很难适应这种变化。,比如很早以前的差分就是一种平稳化操作。序列平稳化能增强数据的可预测性,但这时也会带来一个问题,叫。,通过MLP层进行定义,使得参数可学习,以便于更好的融合到注意力网络中。代码中整体注意力的计算方式与原生Transformer类似,

ViolenceTemper的博客 1499

c with class java_Calling Java Class Methods from C with JNI

http://hildstrom.com/projects/jni/index.htmlCalling Java Class Methods from C with JNIIt never fails. There is some great piece of code that will save you tons of time, but it is written in Java and y...

weixin_39929253的博客 92

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

解决java.lang.IllegalStateException: Calling View methods on another thread than the UI thread

1. 解决WebView当中的UserAgent的问题在android4.4+版本中,webview的使用发生了一些改变:见文档:http://developer.android.com/intl/zh-cn/guide/webapps/migrating.html我们的工程中要收集userAgent,在4.4之后就不能在主线程new webview了,因此使用文档中提供的方法:If you ne...

tanghongchang123的博客 1995

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

What you may need to know while calling Application Module methods from Java EE components such as E

A couple of years back I blogged about Calling Application Module Methods from EJB and MDB. Recently I learned that when a non web client invokes methods defined in EJB or MDB that uses Application

sbtmbj2010的专栏 1052

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

[WebView坑]Calling View methods on another thread than the UI thread

问题 最近接搜狗sdk,调用支付接口的时候闪退,报错 java.lang.IllegalStateException: Must be called from main thread of process 于是放到runOnUiThread中调用 m_context.runOnUiThread(new Runnable() { @Override public void run() { // TODO 搜狗pay } }); 可以拉起支付了,主Activity跪了,从支付宝的WebVi

linxinfa的专栏 2694

【已解决】Calling View methods on another thread than the UI thread.

把你报错的代码行执行在主线程 runOnUiThread(new Runnable() { @Override public void run() { //你的报错代码 } });在4.4之后WebView的使用有点改动

wxx的记录窝 3598

增加aidl 提示error: Methods calling system APIs should rethrow `RemoteException` as `RuntimeException`

原因:这是因为AIDL自动生成的Java文件不满足Android 12 framework API的规范:framework层不能直接暴露原生AIDL文件。修改的方式是在aidl文件上添加/** {@hide} */,如所示,这样就可以解决所有AIDL自动生成的文件。

a258932569的博客 510

java.lang.NoSuchFieldError: NON_BRIDGED_METHODS 错误

今天调试Spring MVC 抛出异常,奇怪的很。java.lang.NoSuchFieldError: NON_BRIDGED_METHODS org.springframework.web.bind.annotation.support.HandlerMethodResolver.init(HandlerMethodResolver.java:90) org.springframe

jTeam的专栏 4496

ajax调用其他方法 methods_vue中实现在外部调用methods的方法(推荐)

1.首先定义一个公共的vue组件;var eventHub = new Vue();2.在事件当前的组件中,在created中,用$on向公共的组件eventHub传递,translate是自定义的,getCardNum(data)是要在外部调用的方法;eventHub.$on('translate', function (data) {that.getCardNum(data);});3.最后在...

weixin_39540704的博客 432

Java方法(Methods)入门讲解(对比C的函数讲解)

Java方法是语句的集合,它们在一起执行一个功能。方法是解决一类问题的步骤的有序组合方法包含于类或对象中方法在程序中被创建,在其他地方被引用方法包含一个方法头和一个方法体。修饰符,这是可选的,告诉编译器如何调用该方法。定义了该方法的访问类型。方法可能会返回值。

2302_79265072的博客 1341

Thymeleaf异常处理Calling methods is forbidden for type

在thymeleaf模板中通过${session.SPRING_SECURITY_LAST_EXCEPTION.getMessage()}获取异常消息时报错。在thymeleaf 3.0.15中将java.lang.Runtime前缀的类加入了黑名单不允许在模板中访问。异常以Exception抛出不要以RuntimeException抛出,其他类似问题通解。

路过君的博客 694

java.lang.Exception: No runnable methods

java.lang.Exception: No runnable methods at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:191) at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:128) at org.ju

weixin_49723367的博客 766

java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path

异常信息 服务器500错误 org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path 'http:...

Joker的博客 2087
上一篇: Linux JNI实例
下一篇: JNIEnv*的常用函数详解
allankin
博客等级 码龄20年 4粉丝 14原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值