Skip to content

Instantly share code, notes, and snippets.

@0x070696E65
Created May 2, 2023 10:53
Show Gist options
  • Save 0x070696E65/c626dcc0705fc5a0e76bba0711f9e11b to your computer and use it in GitHub Desktop.
Save 0x070696E65/c626dcc0705fc5a0e76bba0711f9e11b to your computer and use it in GitHub Desktop.
CatSdkを使ったRoslynのサンプル
var source = @"
using System;
using CatSdk.Utils;
public class SymbolSdk
{
public static string Utf8ToHex(string message)
{
return Converter.Utf8ToHex(message);
}
}
";
var options = CSharpParseOptions.Default
.WithLanguageVersion(LanguageVersion.CSharp8);
var syntaxTree = CSharpSyntaxTree.ParseText(source, options, "SymbolSdk.cs");
var references = new MetadataReference[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Converter).Assembly.Location),
MetadataReference.CreateFromFile(Assembly.LoadFrom("CatSdk.dll").Location),
MetadataReference.CreateFromFile("netstandard.dllの場所"),
MetadataReference.CreateFromFile("System.Runtime.dllの場所"),
};
var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
var compilation = CSharpCompilation.Create(
"SymbolSdk.dll",
new[] { syntaxTree },
references,
compilationOptions);
using var stream = new MemoryStream();
var emitResult = compilation.Emit(stream);
if (emitResult.Success)
{
stream.Seek(0, SeekOrigin.Begin);
var assembly = AssemblyLoadContext.Default.LoadFromStream(stream);
var randomType = assembly.GetType("SymbolSdk");
var method = randomType.GetMethod("Utf8ToHex");
var result = (string)(method.Invoke(null, new object[]{"HELLO"}) ?? throw new InvalidOperationException());
Console.WriteLine($"result: {result}");
}
else
{
IEnumerable<Diagnostic> failures = emitResult.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment