gpt4 book ai didi

java - 我如何实现两个名称相同但参数不同的 JNI 方法?

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:08:11 25 4
gpt4 key购买 nike

我有一个 java 类,其中包含两个名称相同但参数不同的 native 函数。

package com.example;

public class Test {

static {
System.loadLibrary("TestLib");
}

public static native void doSomething(int a);
public static native void doSomething(int a, long b);
}

我的头文件看起来像

#include <jni.h>

#ifndef _TEST_LIB_H_
#define _TEST_LIB_H_

#ifdef __cplusplus
extern "C" {
#endif

JNIEXPORT void JNICALL Java_com_example_Test_doSomething
(JNIEnv *env, jclass clazz, jint a);

JNIEXPORT void JNICALL Java_com_example_Test_doSomething
(JNIEnv *env, jclass clazz, jint a, jlong b);

#ifdef __cplusplus
}
#endif

#endif //_TEST_LIB_H_

还有我的cpp文件

#include "TestLib.h"

JNIEXPORT void JNICALL Java_com_example_Test_doSomething
(JNIEnv *env, jclass clazz, jint a){
Java_com_example_Test_doSomething(env, clazz, a, -1);
}

JNIEXPORT void JNICALL Java_com_example_Test_doSomething
(JNIEnv *env, jclass clazz, jint a, jlong b) {
// implementation
}

它只有一个功能,但在添加第二个具有相同名称和不同参数的功能后,我得到一个错误:

error: conflicting declaration of C function 'void Java_com_example_Test_doSomething(JNIEnv*, jclass, jint, jlong)'
note: previous declaration 'void Java_com_example_Test_doSomething(JNIEnv*, jclass, jint)'

我正在使用 android studio 和实验性 gradle 插件。我做错了什么?

最佳答案

首先,如果您的 native 方法确实将 jclass 作为它们的第二个参数,那么它们应该在 Java 端被声明为 static。否则他们应该采用 jobject(调用它们的实例)而不是 jclass


这是Oracle's documentation说到重载 native 方法的命名:

A native method name is concatenated from the following components: ... for overloaded native methods, two underscores (“__”) followed by the mangled argument signature

因此,您的第二个函数的名称应该是 Java_com_example_Test_doSomething__IJ。您可能还必须将第一个函数的名称更改为 Java_com_example_Test_doSomething__I

关于java - 我如何实现两个名称相同但参数不同的 JNI 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35991911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com