使用jni完成c++代碼調(diào)用
1扼雏、https://blog.csdn.net/yanhenyiduo/article/details/72783709這邊講了基礎(chǔ)的設(shè)置
2宗侦、遇到問題匯總
Q扬跋、需要在target--class文件夾下運行命令行猖毫,javah -jni com.rock.water.WindPdfLibHelper,注意使用類的全限定名稱,生成后將com_rock_water_WindPdfLibHelper.h加入到c++工程
Q言蛇、C++工程中添加jni.h和jni_md.h這兩個文件時,不要直接引用jdk中的文件宵距,把jdk中的文件拷貝到工程中腊尚,工程中直接使用#include "jni.h"完成引用,c++工程中隨意新建個文件包含com_rock_water_WindPdfLibHelper.h消玄,
就可以實現(xiàn)java中定義的函數(shù)跟伏,參數(shù)名稱可以自己隨便加丢胚,env用來新增int數(shù)組,byte數(shù)組受扳,也可以調(diào)用java的代碼
Q携龟、static函數(shù)和非static函數(shù)在c++中的區(qū)別是函數(shù)有個參數(shù)類型是jclass 和jobject
Q、報錯的函數(shù)里有個memcpy把mupdf的unsiged char數(shù)組轉(zhuǎn)化為char數(shù)組勘高,嘗試將char數(shù)據(jù)利用env->jstring NewStringUTF(const char *utf) 轉(zhuǎn)化為string輸出給上層的時候峡蟋,出現(xiàn)以下錯誤
#
# A fatal error has been detected by the Java Runtime Environment:
#
#? EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000007fef2785632, pid=7008, tid=13384
#
# JRE version: Java(TM) SE Runtime Environment (8.0_77-b03) (build 1.8.0_77-b03)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.77-b03 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# C? [WindPdfLib.dll+0x5632]? OutputAndFreeBuffer+0x72
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
#
# If you would like to submit a bug report, please visit:
#? http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
解決方法,buf里放的是unsiged char华望,轉(zhuǎn)化為byte數(shù)組蕊蝗,將byte數(shù)組上傳到上層進(jìn)行utf-8解碼,byte是不同編碼方式的中間數(shù)據(jù)赖舟,說明出現(xiàn)這個問題跟使用的方法有關(guān)系
jbyteArray bytes=env->NewByteArray(buf->len);
env->SetByteArrayRegion(bytes, 0, buf->len, (jbyte*)buf->data);//void SetByteArrayRegion(jbyteArray array, jsize start, jsize len,const jbyte *buf)
fz_close_output(out);
fz_drop_buffer(app->ctx, buf);
return bytes;
3 有問題找官方文檔https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html#wp6212