C和Java程序之间的交互/通信

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

任何人都可以告诉我如何做到这一点?

任何帮助将不胜感激.

解决方法

如果您没有找到JNI’easy’,那么您需要IPC(进程间通信)机制.因此,从您的C流程中,您可以与Java流程进行通信.

你在控制台重定向方面所做的是IPC的一种形式,实质上就是IPC.

由于你发送的内容的性质不是很清楚,很难给你一个很好的答案.但是如果您有“简单”的对象或“命令”可以轻松地序列化为简单的协议,那么您可以使用协议缓冲区等通信协议.

#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’并像普通文件一样读取内容.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...