Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ header to java

Is there any good tool to generate java (+JNI support if needed) from a header file so that a C or C++ library can be used as-is. Kind of a reverse of javah. The real functionality would be in the C/C++, the Java would be only a shim on top for certain users.

I'm no expert on JNI but as far as I can see Javah forces you to do this back to front. It forces you to have JNI-isms penetrating unecessarily into the C code unless you write a conversion layer yourself. And writing a conversion layer by hand is basically a waste of time, since all the information is there in the header file to begin with.

like image 254
idij Avatar asked Sep 22 '10 14:09

idij


People also ask

Is there any header file in Java?

javah generates C header and source files that are needed to implement native methods. The generated header and source files are used by C programs to reference an object's instance variables from native source code. The . h file contains a struct definition whose layout parallels the layout of the corresponding class.

What is C header code?

In C language, header files contain the set of predefined standard library functions. You request to use a header file in your program by including it with the C preprocessing directive “#include”. All the header file have a '. h' an extension. By including a header file, we can use its contents in our program.

How do you create a header file in Java?

You can tell javah to place the header files in a different directory with the -d option. The name of the header file is the Java class name with a . h appended to the end of it. For example, the command shown above will generate a file named HelloWorld.

Can C header files be used in C++?

If you are including a C header file that isn't provided by the system, you may need to wrap the #include line in an extern "C" { /*... */ } construct. This tells the C++ compiler that the functions declared in the header file are C functions.


2 Answers

For C, you can use JNA. You do have to declare function signatures redundantly in Java, but do not have to write any glue code. JNA is very easy to use.

For C or C++, you can use SWIG. SWIG is a little more complex to use, but automatically generates Java wrappers for C++ classes. I'm enjoying it.

like image 184
Andy Thomas Avatar answered Sep 23 '22 05:09

Andy Thomas


JNAerator does exactly that : it reads C/C++/ObjectiveC headers and outputs Java bindings that rely on BridJ (C/C++), JNA (C only) or Rococoa (ObjectiveC, uses JNA).

like image 32
zOlive Avatar answered Sep 22 '22 05:09

zOlive