编译简单字符串

编程入门 行业动态 更新时间:2024-10-26 15:17:30
本文介绍了编译简单字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否只是想知道c ++或c#中是否有任何内置函数可让您在运行时使用编译器?例如,如果我想翻译:

Was just wondering if there are any built in functions in c++ OR c# that lets you use the compiler at runtime? Like for example if i want to translate:

!print "hello world";

进入:

MessageBox.Show("hello world");

然后生成一个exe文件,它将能够显示以上消息?几年前,我已经在网上看到了一个示例项目,但是却找不到了.

and then generate an exe which will then be able to display the above message? I've seen sample project around the web few years ago that did this but can't find it anymore.

推荐答案

可以使用C#.看看CodeProject中的这个示例项目.

It is possible using C#. Have a look at this Sample Project from the CodeProject.

代码提取

private Assembly BuildAssembly(string code) { Microsoft.CSharp.CSharpCodeProvider provider = new CSharpCodeProvider(); ICodeCompiler compiler = provider.CreateCompiler(); CompilerParameters compilerparams = new CompilerParameters(); compilerparams.GenerateExecutable = false; compilerparams.GenerateInMemory = true; CompilerResults results = compiler.CompileAssemblyFromSource(compilerparams, code); if (results.Errors.HasErrors) { StringBuilder errors = new StringBuilder("Compiler Errors :\r\n"); foreach (CompilerError error in results.Errors ) { errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText); } throw new Exception(errors.ToString()); } else { return results.CompiledAssembly; } } public object ExecuteCode(string code, string namespacename, string classname, string functionname, bool isstatic, params object[] args) { object returnval = null; Assembly asm = BuildAssembly(code); object instance = null; Type type = null; if (isstatic) { type = asm.GetType(namespacename + "." + classname); } else { instance = asm.CreateInstance(namespacename + "." + classname); type = instance.GetType(); } MethodInfo method = type.GetMethod(functionname); returnval = method.Invoke(instance, args); return returnval; }

更多推荐

编译简单字符串

本文发布于:2023-10-19 19:25:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508527.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   简单

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!