在尝试运行一个简单的 HelloWorld Unix 可执行文件时:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
}
(通过(在 Mac 上)编译g++ HelloWorld.cpp -o HelloWorld
。该程序在我的 Mac 上使用 ./HelloWorld 并让它在 Java 环境中运行:
(HelloWorld.java -> working)
public class HelloWorld
{
public static void main(String args[])
{
String[] command = new String[]{"/system/bin/chmod", "744",
"/Developer/Java/HelloWorld" };
execute(command);
command = new String[]{"./HelloWorld"};
execute(command);
}
public static void execute(String...command)
{
StringBuilder log = new StringBuilder();
try
{
BufferedReader br;
String line;
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process proc = builder.start();
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
while ( (line = br.readLine()) != null)
System.out.println(line + "\n");
}
catch (IOException e) {
log.append("General IOException:\n" + e.getMessage() + "\n");
}
catch (InterruptedException e) {
log.append("Error:\n" + e.getMessage() + "\n");
}
}
}
在我的 Android 应用程序的 java 代码中,我首先将可执行文件复制到getBaseContext().getDataDir()
,这工作正常。要更改我使用以下的权限:
command = new String[]{"/system/bin/chmod", "744",
getAssetsPath() + "/HelloWorld" };
execute(pv, command);
并尝试通过以下方式运行程序:
command = new String[]{"." + getAssetsPath() + "/HelloWorld"};
terminal(tv, command);
请注意,我使用以下功能:
public File getAssetsDir() {
return getBaseContext().getDataDir();
}
public String getAssetsPath() {
return getAssetsDir().getAbsolutePath();
}
public void execute(TextView tv, String...command)
{
tv.setText("Starting Terminal.\n");
StringBuilder log = new StringBuilder();
try
{
BufferedReader br;
String line;
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process proc = builder.start();
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
while ( (line = br.readLine()) != null)
log.append(line + "\n");
}
catch (IOException e) {
log.append("General IOException:\n" + e.getMessage() + "\n");
}
catch (InterruptedException e) {
log.append("Error:\n" + e.getMessage() + "\n");
}
tv.setText(log.toString());
}
如前所述,这将导致 TextView 内出现以下错误(在 Pixel_XL_API_25 上测试):
syntax error: '__TEXT' unexpected
希望你能帮助我找到这个问题的原因。提前致谢。
编辑:如果您想知道为什么我想将 Unix 可执行文件用于如此简单的事情:这只是为了测试。实际上,我想运行其他更复杂的程序/库,这些程序/库很难通过 ndk 使用,因为这个库没有 cmake,只有“正常”的 make。