用djinni自動生成JNI相關文件

一、djinni是什麼
djinni是個工具,用來生成JNI相關接口。現在很多人都是隻懂java,或者只懂C++,很少有人兩頭都精通;即使兩頭都精通,自己寫JNI接口也很複雜。這時候djinni就能很好的解決這些問題,我們只要按要求配置JNI接口的對象,就能生成兩邊的接口。除了java與C++,還能生成ObjC與C++等接口。

二、環境
java 1.8.0_101
djinni GitHub地址
msys2下載地址
因爲djinni中的一些命令是linux中的命令方式,所以要下載個msys2,在msys2中運行
下載好後打開msys2,cd到djinni根目錄下,輸入以下命令來拉取庫(整個過程時間很長)
src/run --help

用djinni自動生成JNI相關文件

三、編寫djinni配置文件

配置文件中可以配置如下的接口,在C++中具體實現,然後被java或ObjC或其他語言調用

# This interface will be implemented in C++ and can be called from any language.
my_cpp_interface = interface +c {
    method_returning_nothing(value: i32);
    method_returning_some_type(key: string): another_record;
    static get_version(): i32;

    # Interfaces can also have constants
    const version: i32 = 1;
}

如果是C++調用其他語言的接口(+j指java,+o指ObjC),作如下定義

# This interface will be implemented in Java and ObjC and can be called from C++.
my_client_interface = interface +j +o {
    log_string(str: string): bool;
}

也可以定義其中需要一些實體類

my_enum = enum {
    option1;
    option2;
    option3;
}

my_flags = flags {
  flag1;
  flag2;
  flag3;
  no_flags = none;
  all_flags = all;
}

my_record = record {
    id: i32;
    info: string;
    store: set<string>;
    hash: map<string, i32>;

    values: list<another_record>;

    # Comments can also be put here

    # Constants can be included
    const string_const: string = "Constants can be put here";
    const min_value: another_record = {
        key1 = 0,
        key2 = ""
    };
}

another_record = record {
    key1: i32;
    key2: string;
} deriving (eq, ord)

配置好以後調用命令生成

src/run \
   --java-out JAVA_OUTPUT_FOLDER \
   --java-package com.example.jnigenpackage \
   --java-cpp-exception DbxException \ # Choose between a customized C++ exception in Java and java.lang.RuntimeException (the default).
   --ident-java-field mFooBar \ # Optional, this adds an "m" in front of Java field names
   \
   --cpp-out CPP_OUTPUT_FOLDER \
   \
   --jni-out JNI_OUTPUT_FOLDER \
   --ident-jni-class NativeFooBar \ # This adds a "Native" prefix to JNI class
   --ident-jni-file NativeFooBar \ # This adds a prefix to the JNI filenames otherwise the cpp and jni filenames are the same.
   \
   --objc-out OBJC_OUTPUT_FOLDER \
   --objc-type-prefix DB \ # Apple suggests Objective-C classes have a prefix for each defined type.
   \
   --objcpp-out OBJC_OUTPUT_FOLDER \
   \
   --idl MY_PROJECT.djinni

其中有幾個重要的路徑:
JAVA_OUTPUT_FOLDER java文件生成路徑
CPP_OUTPUT_FOLDER cpp文件生成路徑
JNI_OUTPUT_FOLDER jni文件生成路徑
OBJC_OUTPUT_FOLDER objc文件生成路徑(如果需要objc調用的話)
命令執行完成後去這幾個路徑把下面的文件拷貝到項目中使用即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章