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

查看:27
本文介绍了在不使用原始所需程序集的情况下动态编译 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.dllB.dll 是你的程序集?

如果是这样,一种方法是只向这些库公开接口(即,将您的接口和实现放在单独的程序集中),然后传送接口程序集.

这样,就没有什么可以反编译/逆向工程了,它会让编译器很高兴.

要轻松生成所述程序集,您可以使用 Roslyn 来:删除任何私有的(字段、属性、方法等)或不必要的(静态构造函数、内联初始化程序等),用 throw new 替换公共类的公共方法的主体NotImplementedException() 例如,只编译那个.

然后这将产生仅仅是外壳的程序集,但有效地公开正确的接口,这对于编译器来说就足够了.

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天全站免登陆