如何修复JNI内存泄漏?

时间:2019-09-05 08:04:20

标签: c++ java-native-interface

问题在于,当我启动while循环(在C ++中)时,该过程开始占用越来越多的内存。您是否知道清空此内存的方法(可能是发送源代码)?

Java来源:

package Pedo;

public class Main
{
    static int l = 0;
    public static void main(String args[])
    {
        while(true)
        {
        }
    }
}

C ++ JNI来源:

// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include <Windows.h>
#include <iostream>
#include <jni.h>
using namespace std;

BOOL APIENTRY DllMain( HMODULE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
        case DLL_PROCESS_ATTACH:
        {
            HMODULE m_hDllInstance = LoadLibrary("jvm.dll");
            if (m_hDllInstance == 0)
            {
                cout << "The jvm.dll could not be found" << endl;
                getchar();
            }
            else
                cout << "jvm.dll found" << endl;

            JavaVM* jvm;
            JNIEnv* env;

            typedef jint(JNICALL * GetCreatedJavaVMs)(JavaVM * *, jsize, jsize*);
            GetCreatedJavaVMs jni_GetCreatedJavaVMs = (GetCreatedJavaVMs) GetProcAddress(m_hDllInstance, "JNI_GetCreatedJavaVMs");

            jint size = 1;
            jint vmCount;

            jint ret = jni_GetCreatedJavaVMs(&jvm, size, &vmCount);

            jint rc = jvm->AttachCurrentThread((void**)&env, NULL);
            while (true)
            {
                jclass cls = env->FindClass("LPedo/Main;");
                jfieldID fid = env->GetStaticFieldID(cls, "l", "I");
                jobject object = env->GetStaticObjectField(cls, fid);
            }
            jvm->DetachCurrentThread();

            return TRUE;
        }

        case DLL_THREAD_ATTACH:
        case DLL_THREAD_DETACH:
        case DLL_PROCESS_DETACH:
            break;
    }
    return TRUE;
}

由于while循环位于DllMain中,因此显然不会发生内存泄漏。我也在其他线程中尝试过,但是结果是一样的。

0 个答案:

没有答案