如何将 Android C/C++ NDK 的变量从 Android 传递到 C

问题描述 投票:0回答:1

Java 中有一个变量,如何从 C 中分配该变量?我尝试过将变量作为参数传递给函数,但我不知道该怎么做。 这是我尝试过的: 在Java代码中:

String test = "";
stringFromJNI(test);

在C代码中:

#include <jni.h>
#include <string>

extern "C" JNIEXPORT jstring JNICALL
Java_com_mduneau_compass3_MainActivity_stringFromJNI(
    JNIEnv* env,
    jobject obj, /* this */
    jstring test) {
//std::string hello = "Hello from C++";
//return env->NewStringUTF(hello.c_str());
test="HI WORLD";
}

这给出了“意外的参数声明”。错误。

android android-ndk
1个回答
0
投票

您有两种方法来实现它。

  1. 用 C 编写一个函数,返回要分配给 Java 端变量的值。像这样的东西
String test = stringFromJNI(); // stringFromJNI returns a String
  1. 在 Java 端编写一个函数,然后在 C 中调用它,并将您的值作为参数传递。
public void myNewValue (String str) {
    // str is here. you can assign it to other variables
}

您共享的代码是错误的,因为您无法为参数分配新值。

© www.soinside.com 2019 - 2024. All rights reserved.