美文网首页AndroidHot
android jni交互之c层对象指针缓存

android jni交互之c层对象指针缓存

作者: 迷途小书童nb | 来源:发表于2017-08-30 18:09 被阅读28次

    以soundtouch源码为例(https://www.surina.net/soundtouch/sourcecode.html

    java层:

    public final class SoundTouch
    {
        private native final static long newInstance();//初始化
        
        private native final void deleteInstance(long handle);//销毁
    
        private native final void setTempo(long handle, float tempo);//函数调用的时候传入handle,在c层转为相应指针
    
        long handle = 0;//保留c层创建的对象的指针地址
        
        
        public SoundTouch()
        {
            handle = newInstance();     
        }
        
        
        public void close()
        {
            deleteInstance(handle);
            handle = 0;
        }
    }
    

    c层:
    soundtouch-jni.cpp

    #include <jni.h>
    #include <android/log.h>
    
    #define LOGV(...)   __android_log_print((int)ANDROID_LOG_INFO, "SOUNDTOUCH", __VA_ARGS__)
    
    extern "C" DLL_PUBLIC jlong Java_net_surina_soundtouch_SoundTouch_newInstance(JNIEnv *env, jobject thiz)
    {
        return (jlong)(new SoundTouch());//分配对象内存,并把指针地址返回
    }
    
    
    extern "C" DLL_PUBLIC void Java_net_surina_soundtouch_SoundTouch_deleteInstance(JNIEnv *env, jobject thiz, jlong handle)
    {
        SoundTouch *ptr = (SoundTouch*)handle;//将handle转为对象
        delete ptr;
    }
    
    
    extern "C" DLL_PUBLIC void Java_net_surina_soundtouch_SoundTouch_setTempo(JNIEnv *env, jobject thiz, jlong handle, jfloat tempo)
    {
        SoundTouch *ptr = (SoundTouch*)handle;
        ptr->setTempo(tempo);
    }
    

    相关文章

      网友评论

        本文标题:android jni交互之c层对象指针缓存

        本文链接:https://www.haomeiwen.com/subject/utyxjxtx.html