开发者

Java classes to c structs

I have two sources:

  • an xml-file containing definitions of several hundred data structures, basically structs with fields consisting of simple data types (e.g. int, short, boolean, enum), and
  • a c header-file containing the same data structures represented a c structs. (I cannot modify this header-file or the c structs.)

I also have a library, written in c, that is able to use these c structs to perform a specific task.

Last I have a Java application which needs to use this library somehow.

Currently I generate Java classes from the xml-file representing the data structures, now I "just" need to provi开发者_运维知识库de them to the library somehow.

My current approach is to generate jni code, to call a c-function for each struct from Java, accepting the Java generated class as a parameter. Then generate c-code which takes the Java classes and fill in the appropriate fields in the c-structs.

Is this a good approach? Does anybody have suggestions for a simpler approach?

I am considering using sockets and e.g. protobuf, but I do not see this as any simpler.

Thanks in advance for any suggestions.


The solution I am ending up with is using the Javolution struct library

Basically I am generating Java classes that inherits the javolution.io.Struct class from the xml, and declaring the fields appropriately such that javolution can interpret it as struct.

This allows me to do a myJavaStructClass.getByteBuffer() and get a directly mapped byte buffer which has the same memory layout as if the Java "struct" where declared in c. And because it is directly mapped, contains a reference which can be passed directly to native code through JNI.

Javolution also supports both packed and non-packed structs, as well as arbitrary endianness.

Another solution would be to use SWIG to generate Java classes directly from the c header-files, and manage them directly in native code through JNI.


You don't need to use sockets to get value from protobuf here. Serialize into a direct byte buffer passed back and forth between C and Java via JNI. This will be faster and result in writing less annoying code.

As per comment, this still requires copying code between your structs and protobuf structs, but it seems to me that a few CPP macros could make this quite concise. You might even be able to create a code generator that walks some protobuf data structure; it's not impossible that someone else has.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜