Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate C# code with Roslyn and .NET Core

Is there a way to generate C# code using Roslyn with .NET Core. I've tried using the SyntaxFactory from the package Microsoft.CodeAnalysis.CSharp. The problem I'm currently stuck with is getting proper formatted code as text from it.

All the samples I've seen so far use something like

var ws = new CustomWorkspace();
ws.Options.WithChangedOption (CSharpFormattingOptions.IndentBraces, true);
var code = Formatter.Format (item, ws);

The problem here is, that they all use the package Microsoft.CodeAnalysis.CSharp.Workspaces which isn't compatible with .NET Core at the moment. Are there any alternative routes or workarounds for using Roslyn as a code generator with .NET Core?

like image 911
Fionn Avatar asked Aug 29 '16 02:08

Fionn


People also ask

What is C Code generation?

20-sim has a C-Code Generator which automatically converts a complete 20-sim model or submodel into C-Code. The application can be used to generate Matlab™/Simulink™ S-Functions, to generate Stand-Alone executables or to generate input/output functions for use in other C and C++ programs.

Can you write C in MATLAB?

In MATLAB®, you can extend your C and C++ code with a MEX function and call it like any MATLAB built-in function. That means you can use existing C and C++ code without rewriting your algorithms in MATLAB. MEX functions enable C and C++ code to create and modify MATLAB arrays in the MATLAB workspace.

Can Simulink generate C Code?

Simulink® Coder™ generates standalone C and C++ code from Simulink models for deployment in a wide variety of applications. For a list of DSP System Toolbox™ features supported by Simulink Coder, see Blocks Supported for C Code Generation.


1 Answers

The package Microsoft.CodeAnalysis.CSharp.Workspaces 1.3.2 supports netstandard1.3, so it should be compatible with .Net Core. But it depends on Microsoft.Composition 1.0.27, which only supports portable-net45+win8+wp8+wpa81. This framework moniker is compatible with .Net Core, but only if you import it in your project.json.

That means that to make this work, the relevant sections of your project.json should look like this:

"dependencies": {
    "Microsoft.CodeAnalysis.CSharp.Workspaces": "1.3.2"
},
"frameworks": {
  "netcoreapp1.0": {
    "dependencies": {
      "Microsoft.NETCore.App": {
        "type": "platform",
        "version": "1.0.0"
      }
    },
    "imports": "portable-net45+win8+wp8+wpa81"
  }
}
like image 198
svick Avatar answered Oct 14 '22 01:10

svick