简体   繁体   English

将字节数组从 Unity 传递到 Android (C++) 进行修改

[英]Passing byte array from Unity to Android (C++) for modification

I'm trying to use a native library to modify the contents of a byte array (actually uint16 array).我正在尝试使用本机库来修改字节数组(实际上是 uint16 数组)的内容。 I have the array in Unity (C#) and a native library in C++.我在 Unity (C#) 中有数组,在 C++ 中有一个本机库。

I've tried a couple of things, the best I could manage is successfully calling into the native code and being able to return a boolean back to C#.我已经尝试了几件事,我能做到的最好的方法是成功调用本机代码并能够将 boolean 返回到 C#。 The problem comes when I pass an array and mutate it in C++.当我传递一个数组并在 C++ 中对其进行变异时,问题就来了。 No matter what I do, the array appears unmodified in C#.无论我做什么,C# 中的数组都未修改。

Here is what I have on the Unity side:这是我在 Unity 方面的内容:

// In Update().
using (AndroidJavaClass processingClass = new AndroidJavaClass(
"com.postprocessing.PostprocessingJniHelper"))
{
   if (postprocessingClass == null) {
       Debug.LogError("Could not find the postprocessing class.");
       return;
   }

   short[] dataShortIn = ...;  // My original data.
   short[] dataShortOut = new short[dataShortIn.Length];
   Buffer.BlockCopy(dataShortIn, 0, dataShortOut, 0, dataShortIn.Length);

   bool success = postprocessingClass.CallStatic<bool>(
        "postprocess", TextureSize.x, TextureSize.y, 
        dataShortIn, dataShortOut);

   Debug.Log("Processed successfully: " + success);
}

The Unity project has a postprocessing.aar in Plugins/Android and is enabled for the Android build platform. Unity 项目在 Plugins/Android 中有一个 postprocessing.aar,并为 Android 构建平台启用。 I have a JNI layer in Java (which is called successfully):我在 Java 中有一个 JNI 层(调用成功):

public final class PostprocessingJniHelper {

  // Load JNI methods
  static {
    System.loadLibrary("postprocessing_jni");
  }

  public static native boolean postprocess(
      int width, int height, short[] inData, short[] outData);
  private PostprocessingJniHelper() {}

}

The Java code above calls this code in C++.上面的 Java 代码在 C++ 中调用了这个代码。

extern "C" {

JNIEXPORT jboolean JNICALL POSTPROCESSING_JNI_METHOD_HELPER(postprocess)(
    JNIEnv *env, jclass thiz, jint width, jint height, jshortArray inData, jshortArray outData) {
  jshort *inPtr = env->GetShortArrayElements(inData, nullptr);
  jshort *outPtr = env->GetShortArrayElements(outData, nullptr);

  jboolean status = false;
  if (inPtr != nullptr && outPtr != nullptr) {
    status = PostprocessNative(
        reinterpret_cast<const uint16_t *>(inPtr), width, height,
        reinterpret_cast<uint16_t *>(outPtr));
  }

  env->ReleaseShortArrayElements(inData, inPtr, JNI_ABORT);
  env->ReleaseShortArrayElements(outData, outPtr, 0);  

  return status;
}

The core C++ function PostprocessNative seems to also be called successfully (verified by the return value), but all modifications to the data_out are not reflected back in Unity.核心 C++ function PostprocessNative似乎也被成功调用(通过返回值验证),但对 data_out 的所有修改都不会反映在 Unity 中。

bool PostprocessNative(const uint16_t* data_in, int width,
                       int height, uint16_t* data_out) {
  for (int y = 0; y < height; ++y) {
    for (int x = 0; x < width; ++x) {
      data_out[x + y * width] = 10;
    }
  }

  // Changing the return value here is correctly reflected in C#.
  return false;
}

I expect all values of the short[] to be 10, but they are whatever they were before calling JNI.我希望 short[] 的所有值都是 10,但它们与调用 JNI 之前的值相同。

Is this a correct way to pass a Unity array of shorts into C++ for modification?这是将 Unity 短裤数组传递到 C++ 进行修改的正确方法吗?

GetShortArrayElements may pin the Java array in memory, or return a copy of the data. GetShortArrayElements可以将 Java 数组固定在 memory 中,或者返回数据的副本。 So you're supposed to call ReleaseShortArrayElements when you're done using the pointers.因此,您应该在使用完指针后调用ReleaseShortArrayElements

env->ReleaseShortArrayElements(inData, inPtr, JNI_ABORT); // free the buffer without copying back the possible changes
env->ReleaseShortArrayElements(outData, outPtr, 0);       // copy back the content and free the buffer

Firstly, you did not provide any information about your configuration.首先,您没有提供有关您的配置的任何信息。 What is your scripting backend: Mono or IL2CPP ?您的脚本后端是什么: MonoIL2CPP

Secondly, why don't you call C++ code directly from C# ?其次,为什么不直接从C#调用C++代码?

1) Go to: [File] > [build Settings] > [Player Settings] > [Player] and turn on [Allow 'unsafe' Code] property. 1) Go 到: [File] > [build Settings] > [Player Settings] > [Player]并打开[Allow 'unsafe' Code]属性。

2) After building the library, copy the output.so file(s) into the Assets/Plugins/Android directory in your Unity project. 2)构建库后,将 output.so 文件复制到 Unity 项目的Assets/Plugins/Android目录中。

在此处输入图像描述

C# code: C# 代码:

using UnityEngine;
using UnityEngine.UI;
using System.Runtime.InteropServices;
using System;


public class CallNativeCode : MonoBehaviour
{
    [DllImport("NativeCode")]
    unsafe private static extern bool PostprocessNative(int width, int height, short* data_out);

    public short[] dataShortOut;
    public Text TxtOut;

    public void Update()
    {
        dataShortOut = new short[100];
        bool o = true;

        unsafe
        {
            fixed (short* ptr = dataShortOut)
            {
                o = PostprocessNative(10, 10, ptr);
            }
        }

        TxtOut.text = "Function out:  " + o + " Array element 0: " + dataShortOut[0];
    }
}

C++ code: C++ 代码:

#include <stdint.h>
#include <android/log.h>

#define LOG(...) __android_log_print(ANDROID_LOG_VERBOSE, "0xBFE1A8", __VA_ARGS__)


extern "C"
{
    bool PostprocessNative(int width, int height, short *data_out)
    {
        for (int y = 0; y < height; ++y)
        {
            for (int x = 0; x < width; ++x)
            {
                data_out[x + y * width] = 10;
            }
        }

        LOG("Log: %d", data_out[0]);

        // Changing the return value here is correctly reflected in C#.
        return false;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM