3

私は現在、マイクロマシニング/ファインメカニクスを行う研究機関にいて、ラボの 1 つで使用している現在のセットアップ用のコントローラー ソフトウェアを開発するように依頼されました。

ナノステージと、中央アプリケーションで制御する必要があるシャッターやフィルターホイールなどのその他の機器があります。ソフトウェアは実行用に事前設定されたジョブを提供します。これは基本的に、ステージ用のコマンドを生成するアルゴリズムであり、レーザーを使用してさまざまなパターンをサンプル (長方形、円柱など) に書き込むために使用されます。

この定義済みジョブのリストを実行時に拡張する何らかの可能性を提供できれば素晴らしいと思います。つまり、提供されているようなアルゴリズムをユーザーが追加できるということです。

私は C# の初心者 (および一般的にはデスクトップ アプリケーションの初心者) であるため、これを行う方法やどこから調べればよいかについてヒントをいただければ、非常に感謝しています。

4

1 に答える 1

2

この「スクリプト」は、.NET 統合 C# コンパイラを使用して実行しました。
多少の作業は必要ですが、基本的には次のようになります。

    public Assembly Compile(string[] source, string[] references) {
        CodeDomProvider provider = new CSharpCodeProvider();
        CompilerParameters cp = new CompilerParameters(references);
        cp.GenerateExecutable = false;
        cp.GenerateInMemory = true;
        cp.TreatWarningsAsErrors = false;

        try {
            CompilerResults res = provider.CompileAssemblyFromSource(cp, source);
            // ...
            return res.Errors.Count == 0 ? res.CompiledAssembly : null;
        }
        catch (Exception ex) {
            // ...
            return null;
        }
    }

    public object Execute(Assembly a, string className, string methodName) {
        Type t = a.GetType(className);
        if (t == null) throw new Exception("Type not found!");
        MethodInfo method = t.GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);          // Get method
        if (method == null) throw new Exception("Method '" + methodName + "' not found!");                                  // Method not found

        object instance =  Activator.CreateInstance(t, this);
        object ret = method.Invoke(instance, null); 
        return ret;
    }

実際のコードは、コード エディターなど、さらに多くのことを行います。
それは私たちの工場で何年もの間非常にうまく機能しています。

このように、ユーザーはスクリプトに C# を使用するため、同じ API を使用できます。

.csプレーンファイルのようなコード テンプレートを使用できます。実行時にビルドされ、 のsourceパラメータに提供されますCompile

using System;
using System.IO;
using ...

namespace MyCompany.Stuff {
    public class ScriptClass {
        public object main() {

            // copy user code here
            // call your own methods here

        }

        // or copy user code here

        private int test(int x) { /* ... */ }
    }
}

例:

string[] source = ??? // some code from TextBoxes, files or whatever, build with template file...
string[] references = new string[] { "A.dll", "B.dll" };

Assembly a = Compile(source, references);
object result = Execute(a, "MyCompany.Stuff.ScriptClass", "main");
于 2013-07-18T12:45:37.970 に答える