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