3

我有一个用 Java 编写的应用程序和一些带有系统挂钩的本机 C++ 代码。这两个必须互相交流。我的意思是 C++ 子程序必须向 Java 发送一些数据。如果可能的话,我会用一种语言写整件事。我现在正在做的事情真的很愚蠢,但是很有效。我正在隐藏 C++ 程序的窗口并将其数据发送到它的标准输出,然后我正在使用 Java 的标准输入读取该输出!!!好的,我知道 JNI 是什么,但我正在为此寻找更容易的东西(如果有的话)。

谁能告诉我如何做到这一点?

任何帮助将不胜感激。

4

3 回答 3

3

Sockets & Corba是我想到的两种技术。

另外,试试Google 的 Protocol BuffersApache Thrift

于 2010-12-31T19:26:03.307 回答
2

我想到了两种方法:

1)创建两个进程并使用任何合适的IPC;

2) 将 C++ 应用程序编译成动态库并导出具有标准 C 接口的函数,这些函数应该可以从任何语言调用。

于 2010-12-31T19:45:25.793 回答
2

如果你没有发现 JNI 'easy',那么你需要一个 IPC(进程间通信)机制。因此,从您的 C++ 进程中,您可以与您的 Java 进程进行通信。

您对控制台重定向所做的事情是 IPC 的一种形式,本质上就是 IPC。

由于您发送的内容的性质并不完全清楚,因此很难给您一个好的答案。但是,如果您有可以轻松序列化为简单协议的“简单”对象或“命令”,那么您可以使用通信协议,例如protocol buffers.

#include <iostream>
#include <boost/interprocess/file_mapping.hpp>

// Create an IPC enabled file
const int FileSize = 1000;

std::filebuf fbuf;
fbuf.open("cpp.out", std::ios_base::in | std::ios_base::out 
                          | std::ios_base::trunc | std::ios_base::binary); 
// Set the size
fbuf.pubseekoff(FileSize-1, std::ios_base::beg);
fbuf.sputc(0);

// use boost IPC to use the file as a memory mapped region
namespace ipc = boost::interprocess;
ipc::file_mapping out("cpp.out", ipc::read_write);

// Map the whole file with read-write permissions in this process
ipc::mapped_region region(out, ipc::read_write);

// Get the address of the mapped region
void * addr       = region.get_address();
std::size_t size  = region.get_size();

// Write to the memory 0x01
std::memset(addr, 0x01, size);

out.flush();

现在您的 java 文件可以打开 'cpp.out' 并像普通文件一样读取内容。

于 2010-12-31T20:12:59.890 回答