动态编译C#代码,而不使用原始所需的程序集 [英] Compile C# code dynamically without using original required assemblies

查看:460
本文介绍了动态编译C#代码,而不使用原始所需的程序集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的软件中编译由最终用户动态编写的C#代码。为了编译代码,我需要添加一些程序集作为CompilerParameters的引用。

  CompilerParameters loParameters = new CompilerParameters 
loParameters.ReferencedAssemblies.Add(C:\A.dll)
loParameters.ReferencedAssemblies.Add(C:\B.dll)

因此,我应该用我的软件发布这些程序集(A.dll和B.dll),但由于安全原因,

注意1 :我可以删除所需的程序集中的方法的实现。 (A和B),但我的程序集非常大,我不能手动执行。



注2 :我知道混淆,我不想使用它。



注3 :我只需要成功编译代码,我不想运行

解决方案

我假设 A.dll 和<$



如果是这样,一种方法是仅将接口暴露给这些库即将接口和实现放在单独的程序集中),然后运行接口程序集。



这样,反编译/反向工程就没有任何反应,



要生成所述程序集,您可以使用Roslyn:删除任何私有(字段,属性,方法等)或不必要的(静态构造函数, ,etc),用public new NotImplementedException()替换公共类的公共方法的主体,并只编译那个。



这样会生成只是shell的程序集,但有效地暴露正确的接口,这对于编译器是足够的。


I'm compiling the C# code written by end-user dynamically in my software. In order to compile the code I need to add some assemblies as reference to CompilerParameters.

CompilerParameters loParameters = new CompilerParameters();
loParameters.ReferencedAssemblies.Add("C:\A.dll")
loParameters.ReferencedAssemblies.Add("C:\B.dll")

Therefore I should release these assemblies ("A.dll" and "B.dll") with my software, but because of security reason I don't want the user can access the source of these assemblies by reverse engineering.

Note 1: I can remove the implementation of methods in required assemblies (A and B) but my assemblies are very large and I can't do it manually.

Note 2: I know about obfuscation but I don't want to use that.

Note 3: I just need to compile the code successfully and I don't want to run it.

解决方案

I assume that the A.dll and B.dll are assemblies that are yours?

If so, an approach would be to only expose interfaces to these libraries (ie place your interfaces and implementations in separate assemblies) and then ship the interface assemblies.

This way, there would be nothing to decompile / reverse engineer and it would allow the compiler to be happy.

To generate said assemblies easily, you could use Roslyn to: remove anything private (fields, properties, methods etc) or unnecessary (static constructors, inline initialisers, etc), replace the body of public methods of public classes with throw new NotImplementedException() for example and compile only that.

This would then produce assemblies that were merely shells, but effectively exposing correct interfaces which would be sufficient for a compiler.

这篇关于动态编译C#代码,而不使用原始所需的程序集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆