NDK和SDK之间低于API级别26的共享内存

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

用c ++编写的库可产生连续的数据流,并且必须将其移植到不同的平台上。现在将lib集成到android应用程序中,我试图在NDK和SDK之间创建共享内存。

下面是工作片段,

本地代码:

#include <jni.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <linux/ashmem.h>
#include <android/log.h>
#include <string>

char  *buffer;
constexpr size_t BufferSize=100;
extern "C" JNIEXPORT jbyteArray JNICALL
Java_test_com_myapplication_MainActivity_getSharedBufferJNI(
        JNIEnv* env,
        jobject /* this */) {

    int fd = open("/dev/ashmem", O_RDWR);

    ioctl(fd, ASHMEM_SET_NAME, "shared_memory");
    ioctl(fd, ASHMEM_SET_SIZE, BufferSize);

    buffer = (char*) mmap(NULL, BufferSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

    char *c = "Hello World 123 speaking";

    std::strncpy(buffer,c,BufferSize);

    return static_cast<jbyteArray>(env->NewDirectByteBuffer(buffer, BufferSize));
}

extern "C" JNIEXPORT void JNICALL
Java_test_com_myapplication_MainActivity_TestBufferCopy(
        JNIEnv* env,
        jobject /* this */) {

   for(size_t i=0;i<BufferSize;i = i+2) {
       __android_log_print(ANDROID_LOG_INFO, "native_log", "Count %d value:%d", i,buffer[i]);
   }
}

SDK代码:

//MainActivity.java
public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.

    static {
        System.loadLibrary("native-lib");
    }

    final int BufferSize = 100;
    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ByteBuffer byteBuffer = getSharedBufferJNI();
        byte[] b = byteBuffer.array();
        String s = new String(b,StandardCharsets.UTF_8 );
        Log.i("sdk_log",s);


        for(int i =0; i<BufferSize;i++) {
            Log.i("sdk_log",i+" "+byteBuffer.get(i));
            byteBuffer.put(i, (byte) (i+10));
        }
        TestBufferCopy();
    }


    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native ByteBuffer getSharedBufferJNI();
    public native int TestBufferCopy();
}

问题:

  1. Accessing primitive arrays从Java到本机仅在垃圾回收器支持固定的情况下才引用。其他方法是否正确?
  2. Android平台是否保证ALWAYS参考从NDK共享到SDK,而没有冗余副本?
  3. 可以在cjava之间映射存储器的另一种方式>

用c ++编写的库可产生连续的数据流,并且必须将其移植到不同的平台上。现在将lib集成到android应用程序中,我试图在...

android c sdk android-ndk shared-memory
1个回答
0
投票

让我总结一下我的发现,

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