0

Are there any tools that I can use to parse c struct to java interface automatically? an example would be:

typedef struct C {
    int x;
    byte y;
}C;

//Java
interface C {
    public int x();
    public byte y();
    public void x(int val);
    public void y(byte val);
}
2
  • There is no byte (or btye) type in C right? Commented Feb 10, 2014 at 15:11
  • It's not directly about code transformation because it has a slightly different syntax but might be one useful tool in your pipeline: github.com/marc-christian-schulze/structs4java Commented Sep 10, 2016 at 10:21

2 Answers 2

1

Yes, try regular expression replaces. In Java for example:

String javaCode = cCode.replaceAll("(\\w+) +(\\w+);", "public void $1 $2();\n    public $1 x($1 $2);");

Demo here: http://regexr.com?388h8

Now, just a minimal effort is needed to change the syntax of the struct definition itself.

Sign up to request clarification or add additional context in comments.

1 Comment

this is only an example, with a big struct, regular expression is not a solution.
0

Javolution is a library that provides this kind of functionality in an easy way, example taken from the documentation:

public enum Gender { MALE, FEMALE };
public static class Date extends Struct {
  public final Unsigned16 year = new Unsigned16();
  public final Unsigned8 month = new Unsigned8();
  public final Unsigned8 day   = new Unsigned8();
}
public static class Student extends Struct {
  public final Enum32<Gender>       gender = new Enum32<Gender>(Gender.values());
  public final UTF8String           name   = new UTF8String(64);
  public final Date                 birth  = inner(new Date());
  public final Float32[]            grades = array(new Float32[10]);
  public final Reference32<Student> next   =  new Reference32<Student>();
}

2 Comments

Javolution and other library(JNA) only provide the way of converting, they are not tools for automatically convert from c to Java
If you want to avoid translating such a specific thing because you are lazy / have many of them the only solution I see is to write a simple parser in lex/yacc or antlr. If a tool doesn't exist, just roll your own. A lexer/parser to translate them would be really easy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.