繁体   English   中英

有没有办法从java执行Objective-C应用程序?

[英]Is there a way execute an Objective-C application from java?

我有一个已经存在的Objective-C控制台应用程序。 我不是开发它的人,因此我无法轻松访问代码。 所以更改代码可能不是一个选项,但我所知道的是,对于编译,它需要Cocoa和SystemConfiguration。 (我在电子邮件中被告知)一旦运行,它会有一个等待命令的提示,并且在该命令之后有一个文本输出结果。 有没有办法,我可以采取这个应用程序并在java中运行它并捕获输出?

我之前从未做过OSX开发,但我知道C代码可以很好地与Java一起工作,而Obj-c是C的超集,但是对于框架要求,似乎很清楚在代码中的某个地方使用了对象。

我见过类似rococoa的东西,但是在一段时间内没有更新(2009)它是否仍然适用于山狮?

当你说你有一个Objective-C应用程序时,你的意思是你有一个为Mac OS编译的二进制/可执行文件?

如果是这样,您可以通过Class ProcessBuilder来创建操作系统进程。

Process p = new ProcessBuilder("myCommand", "myArg").start();

注意:此解决方案仅适用于Mac OS X.此外,您可能遇到一些安全问题,因为Java喜欢在沙箱中运行。

如果你想创建一个子进程,并在它和你的主程序之间交换信息,我认为以下代码将对你有所帮助。

它通过调用二进制/可执行文件创建子进程,然后将某些内容(例如命令)写入其输入流并读取一些文本:

import java.io.*;


public class Call_program
{
    public static void main(String args[])
    {
        Process the_process = null;
        BufferedReader in_stream = null;
        BufferedWriter out_stream = null;

        try {
            the_process = Runtime.getRuntime().exec("...");   //replace "..." by the path of the program that you want to call
        }
        catch (IOException ex) {
            System.err.println("error on exec() method");
            ex.printStackTrace();  
        }

        // write to the called program's standard input stream
        try
        {
            out_stream = new BufferedWriter(new OutputStreamWriter(the_process.getOutputStream()));
            out_stream.write("...");     //replace "..." by the command that the program is waiting for
        }
        catch(IOException ex)
        {
            System.err.println("error on out_stream.write()");
            ex.printStackTrace();  
        }

        //read from the called program's standard output stream
        try {
            in_stream = new BufferedReader(new InputStreamReader(the_process.getInputStream()));
            System.out.println(in_stream.readLine());   //you can repeat this line until you find an EOF or an exit code.
        }
        catch (IOException ex) {
            System.err.println("error when trying to read a line from in_stream");
            ex.printStackTrace();  
        }
    }
}

REF。

http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=%2frzaha%2fiostrmex.htm

如果这个列表是全面的,那么就没有纯粹的Objective-C解决方案。

http://en.wikipedia.org/wiki/List_of_JVM_languages

你的下一个选择是从Java调用C的解决方案 - 它本身很容易谷歌,所以我不会在这里包含信息 - 或者更多的解耦解决方案(很可能是你想要的)例如使用消息总线,例如ZeroMQ或RabbitMQ。

我强烈建议避免桥接两种语言,除非您有特别不寻常的架构或硬件要求。 桥接两种语言是O(n ^ 2)API,用于学习语言数量,实现消息队列是O(n)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM