Ответ 1
Хорошо, я нашел решение, которое кажется довольно удобным, но, вероятно, есть более правильные пути;
CMakeLists.txt по умолчанию помещается внутри myAppProject/app, поэтому я добавил эту строку в CMakeLists.txt:
set(EXECUTABLE_OUTPUT_PATH "${CMAKE_CURRENT_SOURCE_DIR}/src/main/assets/${ANDROID_ABI}")
полное приложение /CMakeLists.txt:
cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_VERBOSE_MAKEFILE on)
# set binary output folder to Android assets folder
set(EXECUTABLE_OUTPUT_PATH "${CMAKE_CURRENT_SOURCE_DIR}/src/main/assets/${ANDROID_ABI}")
add_subdirectory (src/main/cpp/mylib)
add_subdirectory (src/main/cpp/mybinary)
полное приложение /src/main/cpp/mybinary/CMakeLists.txt:
add_executable(mybinary ${CMAKE_CURRENT_SOURCE_DIR}/mybinary.cpp)
# mybinary, in this example, has mylib as dependency
target_link_libraries( mybinary mylib)
target_include_directories (mybinary PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
полное приложение /src/main/cpp/mylib/CMakeLists.txt:
add_library( # Sets the name of the library.
mylib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
# Associated headers in the same location as their source
# file are automatically included.
${CMAKE_CURRENT_SOURCE_DIR}/mylib.cpp )
target_include_directories (mylib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
Таким образом, любой исполняемый двоичный файл скомпилируется непосредственно в папке с ресурсами внутри подпапки, имя которой является целевым ABI, например:
assets/armeabi/mybinary
assets/x86_64/mybinary
...
Чтобы использовать правильную двоичную копию внутри приложения, следует выбрать правильный двоичный файл:
String abi;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
abi = Build.SUPPORTED_ABIS[0];
} else {
//noinspection deprecation
abi = Build.CPU_ABI;
}
String folder;
if (abi.contains("armeabi-v7a")) {
folder = "armeabi-v7a";
} else if (abi.contains("x86_64")) {
folder = "x86_64";
} else if (abi.contains("x86")) {
folder = "x86";
} else if (abi.contains("armeabi")) {
folder = "armeabi";
}
...
AssetManager assetManager = getAssets();
InputStream in = assetManager.open(folder+"/" + "mybinary");
Затем двоичный файл должен быть скопирован в папку с ресурсами с правильными разрешениями на выполнение:
OutputStream out = context.openFileOutput("mybinary", MODE_PRIVATE);
long size = 0;
int nRead;
while ((nRead = in.read(buff)) != -1) {
out.write(buff, 0, nRead);
size += nRead;
}
out.flush();
Log.d(TAG, "Copy success: " + " + size + " bytes");
File execFile = new File(context.getFilesDir()+"/mybinary");
execFile.setExecutable(true);
Что все!
UPDATE: gradle.build файл:
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25"
defaultConfig {
applicationId "com.myapp.example"
minSdkVersion 10
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags ""
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
defaultConfig {
externalNativeBuild {
cmake {
targets "mylib", "mybinary"
arguments "-DANDROID_TOOLCHAIN=clang"
cFlags "-DTEST_C_FLAG1", "-DTEST_C_FLAG2"
cppFlags "-DTEST_CPP_FLAG2", "-DTEST_CPP_FLAG2"
abiFilters 'armeabi', 'armeabi-v7a', 'x86', 'x86_64'
}
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.android.support:design:25.0.0'
compile 'com.android.support:recyclerview-v7:25.0.0'
compile 'com.android.support:cardview-v7:25.0.0'
compile 'eu.chainfire:libsuperuser:1.0.0.201607041850'
}