使用 NDK 在 Android 中创建临时文件 [英] Creating temporary files in Android with NDK
问题描述
我目前正在开发一个基于 C、基于 NDK 的 Android 应用程序.此应用程序需要创建临时文件.在常规 Linux 系统上,我会使用 tmpfile
来确保这些文件在临时目录中正确创建并在进程结束时清理.
I am currently working on a C-based, NDK-based, Android application. This application needs to create temporary files. On a regular Linux system, I would use tmpfile
to ensure that these files are properly created in a temporary directory and cleaned-up at process end.
但是,我对各种 Android 设备的调查似乎表明
However, my investigations on various Android devices seem to indicate that
tmpfile
总是失败;- 没有
/tmp
目录; - 目录
/data/local/tmp
并不存在于所有 Android 变体上; - 没有设置
TEMP
环境变量; mkstemp
并不比tmpfile
好用.
tmpfile
always fails;- there is no
/tmp
directory; - directory
/data/local/tmp
isn't present on all variants of Android; - there is no
TEMP
environment variable set; mkstemp
doesn't work any better thantmpfile
.
现在,我确信我可以一起破解一些东西,但是看到 SDK 为 Java 应用程序提供 context.getCacheDir
和 File.createTempFile
,我希望在 C 级别有一个等价物.
Now, I'm sure that I could hack something together, but seeing that the SDK offers context.getCacheDir
and File.createTempFile
for Java applications, I hope that there is an equivalent at C-level.
有人知道创建临时文件的可靠且跨 Android 的良好方法吗?
Does anyone know of a good reliable and cross-Android method for creating a temporary file?
推荐答案
我们发现最好的方法是在启动时调用 Context.getCacheDir
,用 getAbsolutePath
获取它的路径code>,然后调用 JNI 函数将该路径存储在全局中.任何想要创建临时文件的函数只需将合适的临时文件名附加到该路径即可.
The best way we've found is to call Context.getCacheDir
on startup, get its path with getAbsolutePath
, then call a JNI function to store that path in a global. Any function that wants to create a temporary file simply appends a suitable temporary file name to that path.
如果你真的想从 JNI 中获取它,另一种选择是将 Context
传递给 JNI 函数并使用一堆 GetMethodID
/CallObjectMethod
的东西在 Java 中回调到 getCacheDir
,但前一种方法要简单得多.
If you really want to fetch it from JNI another alternative would be to pass in a Context
to a JNI function and use a bunch of GetMethodID
/ CallObjectMethod
stuff to call back into Java to getCacheDir
, but the former approach is a lot simpler.
很遗憾,目前似乎没有更优雅的解决方案.
Unfortunately, there does not appear to be a more elegant solution at the moment.
这篇关于使用 NDK 在 Android 中创建临时文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!