Question

I would like to generate some wrapper code based on C++ types. I basically would like to parse some C++ headers, get the types, classes and their fields defined in the headers, and generate some code based on them.

What would be the easiest way to parse C++ and get type information? I thought about using the Clang C++ parser, but I couldn't make a working hello world in a couple of hours, so I gave up for the time being.
Could you advise any other way to parse C++, or if Clang is the easiest solution, could you point me to a simple getting started guide to be able to parse C++ types with it?

(basically any technology would be ok, C++, Java, C#, etc., this would be part of a command line tool)

Was it helpful?

Solution

Clang is definitely the easiest option. Consider using cindex python bindings, it's pretty straightforward. Alternatively, you could get an older version of clang which still features an xml backend.

EDIT: the link above seems to be down, so here is a link to the google cache of it.

Another link suggested in the comments: http://www.altdevblogaday.com/2014/03/05/implementing-a-code-generator-with-libclang/

OTHER TIPS

Unless your object is to verify correctness, or the code involves advanced template stuff, consider using the XML output of DOxygen or GCC_XML. Alternatively, consider clang, even if that's what you found too complex. Note that for clang it might be best to work in *nix-land.

If your generation tool is in Java, consider using the parser from the Eclipse CDT. my set of dependencies are:

  • com.ibm.icu_4.4.2.v20110823.jar
  • org.eclipse.cdt.core_5.3.2.201202111925.jar
  • org.eclipse.equinox.common_3.6.0.v20110523.jar

(these are from an old Eclipse version, because I have a dependency on old java class versions), but taking from the latest CDT wil do.

parsing involves:

FileContent reader;
reader = FileContent.createForExternalFileLocation(fullPath);
IScannerInfo info = new ScannerInfo(definedSymbols, includePaths);
return GPPLanguage.getDefault().getASTTranslationUnit(reader, info, FilesProvider.getInstance(), null, 0,log);

This returns an IASTTranslationUnit that can be accessed through a Visitor pattern (ASTVisitor).

I cannot comment on the accuracy of the parsing in corner scenarios, because so far I've been generating code based on simple C++ structure definitions.

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