Question

I've got an app written in Java and some native C++ code with system hooks. These two have to communicate with each other. I mean the C++ subprogram must send some data to the Java one. I would've written the whole thing in one language if it was possible for me. What I'm doing now is really silly, but works. I'm hiding the C++ program's window and sending it's data to it's standard output and then I'm reading that output with Java's standard input!!! Ok, I know what JNI is but I'm looking for something easier for this (if any exists).

Can anyone give me any idea on how to do this?

Any help will be greatly appreciated.

Was it helpful?

Solution

If you don't find JNI 'easy' then you are in need of an IPC (Inter process communication) mechanism. So from your C++ process you could communicate with your Java one.

What you are doing with your console redirection is a form of IPC, in essence that what IPC.

Since the nature of what you are sending isn't exactly clear its very hard to give you a good answer. But if you have 'simple' Objects or 'commands' that could be serialised easily into a simple protocol then you could use a communication protocol such as 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();

Now your java file could open 'cpp.out' and read the contents like a normal file.

OTHER TIPS

Sockets & Corba are two techniques that come to mind.

Also, try Google's Protocol Buffers or Apache Thrift.

Two approaches off the top of my head:

1) create two processes and use any suitable IPC;

2) compile C++ app into dynamic library and export functions with standard C interface, those should be callable from any language.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top