在NDK共享内存区域 [英] Shared memory region in NDK

查看:458
本文介绍了在NDK共享内存区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个共享的内存块(一个 ashmem 区域)被映射和从本地code访问。我也想被多个应用此块。我也希望它工作在SDK 7级(Android 2.1的)

I want to have a shared memory block (an ashmem region) that's mapped and accessed from native code. I also want this block to be used by several applications. I also want it to work on SDK level 7 (Android 2.1)

有两种途径。我可以创建本地code的ashmem区域;但随后的问题是 - 我怎么整数关口文件描述符到另一个进程?您可以通过元帅的FileDescriptor 对象包裹,但没有办法,构成一个围绕原始FD。还有 ParcelFileDescriptor ,支持各地建设和获取整数FD的,但相关的方法只支持SDK 12级甚至更高。

There are two routes. I can create an ashmem region in native code; but then the question is - how do I pass an integer file descriptor to another process? You can marshal FileDescriptor objects via a Parcel, but there's no way to construct one around a raw FD. There's also ParcelFileDescriptor which supports constructing around and retrieving integer FD's, but the relevant methods are only supported in SDK level 12 or even higher.

另外,我可以创建一个 MemoryFile 。有一个的fugly方式在地块周围通过。但我怎么检索它文件描述符,使原生code的东西的mmap()

Alternatively, I can create a MemoryFile. There's a fugly way to pass it around in Parcels. But how do I retrieve a file descriptor from it so that native code has something to mmap()?

推荐答案

在所有版本的Andr​​oid,因为1.5到4.1,的FileDescriptor 有一个 INT 称为数据成员描述。这是包私人早期版本的Andr​​oid,私人最近的例子。带着几分刻意的访问控制颠覆,您可以访问它 - 无论是通过反射,或通过JNI。每个人都可以绕过访问控制 - 如果反射,通过 Field.setAccessible(),如果JNI的 - 默认

On all versions of Android since 1.5 to 4.1, FileDescriptor has an int data member called descriptor. It's package-private on earlier versions of Android, private on recent ones. With a bit of deliberate access control subversion, you can access it - either via reflection, or via JNI. Each can bypass access control - in case of reflection, via Field.setAccessible(), in case of JNI - by default.

考虑到这一点,您可以构造的FileDescriptor 围绕本地FD就好了。构造一个空白的,然后设置描述。这就是比特和建设的时候,Android的code件事情。

With that in mind, you can construct a FileDescriptor around a native FD just fine. Construct a blank one, then set descriptor. That's what bits and pieces of Android code do when constructing those.

这肮脏的黑客是否会打破最终,谁也不知道。幸运的是,它不是一个核心部分,在我的情况下的功能 - 有一些优雅降级

Whether this dirty hack will break eventually, who knows. Fortunately, it's not a core piece of functionality in my case - there's some graceful degradation.

人们可以有条件地聘请支持 ParcelFileDescriptor 方法,如果平台允许,使用字段访问黑客作为后备。这样一来,这将是相对面向未来。

One may conditionally employ supported ParcelFileDescriptor methods, if the platform allows, using the field access hack as a fallback. This way, it'll be relatively future proof.

这篇关于在NDK共享内存区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆