如何将文件路径从.java类文件传递到本机jni文件



我想使用jni将文件路径从Java类传递到本机文件。在本机实现文件中,我想检查文件是否存在。

这是我的java文件:

public class FileNative extends Activity {
    String fpath = "storage/emulated/0/Download/view.pdf";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String str1 =null;
            Log.d("Click","The button has been clicked to open the file");
            str1 = ndkopenfile(fpath);
        }
    }
    public native String ndkopenfile(String fpath);
    static {
        System.loadLibrary("file-jni");
    }
}

这是我的C++文件:

JNIEXPORT jstring JNICALL Java_com_example_filewithnative_FileNative_ndkopenfile(JNIEnv *env, jobject obj , jstring path)
{
    const char* jnamestr = env->GetStringUTFChars(path, 0);
    char retPath[20];
    FILE* fp = fopen(jnamestr,"w+");
    if(fp)
    {
        return env->NewStringUTF(jnamestr);
    }
    else
    {
        return env->NewStringUTF("Error opening file!");
    }
}

请帮我弄清楚为什么这不起作用。谢谢

首先,

public native String ndkopenfile(String fpath); static{ System.loadLibrary("file-jni"); }

应该在FileNative类中。其次,您必须将本机代码编译为您想要支持的任何架构的静态库(例如:armeabi、armeabi-v7a、x86),并将它们放在apk中的适当目录中。

你真的应该在安卓NDK上读一读,也许可以学习一两个教程。https://developer.android.com/tools/sdk/ndk/index.html#GetStarted

相关内容

最新更新