Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create C style union in java?

Tags:

java

c

I have to convert one of my code segment from C to java. Code is given below.

union commandString{
    char commndStr[20];
    struct{
        char commnd[4];
        char separator1;
        char agr1[5];
        char separator2;
        char arg2[3];
        char separator3;
        char additionalArg[5];
    };
};

I don't want to use any explicit parser or I do not want to use

System.arraycopy

method. Is there any way to do that in my preferred way?

like image 464
Saikat Avatar asked Jul 19 '14 05:07

Saikat


2 Answers

The Java language does not support unions or direct control memory layout the way that languages like C do directly.

However Oracle does offer a backdoor that was added in Java 5 that can be used by using the class sun.misc.Unsafe. It takes a bit of work, the full details have been documented by Martin Thompson on his blog.

The other option would be to write it in C and access it from Java as native functions via JNI.

like image 139
Chris K Avatar answered Oct 19 '22 09:10

Chris K


The best library for doing Struct and Union would be Javolutions which has been around for many years. These were designed to do this.

I suggest if you are going to use these Unsafe you wrap it up in a library which abstracts it away. This can avoid continuously running into bugs which crash your JVM (and I mean crash in the sense a C programmer would understand)

I have a library called Java-Lang which allows you to do the sort of things Java doesn't normally allow such as 63 bit sized off heap and memory mapped, thread safe off heap operations, sharing of memory between JVM on the same machine. And as I said, I use my own library to abstract away use of Unsafe.

like image 2
Peter Lawrey Avatar answered Oct 19 '22 08:10

Peter Lawrey