I have created an application that allows dynamically executing code. A
lot of the concepts are based on Rick Strahl's article in
http://www.west-wind.com/presentatio...ynamicCode.htm which
creates code in alternate AppDomains to eliminate the memory leak caused
by loading assemblies on the main AppDomain and not being able to unload
them.
Everything works fine, except that I am having trouble passing objects
by reference to my dynamic code.
Here is a description of the problem:
The first thing I tried is to keep an instance of an object inside the
script that could be requested by the calling application. I created a
class called ScriptingObject in a dll that was included both the calling
application and the dynamic code.
public class ScriptingObject
{
private string current = "";
public string Current
{
get { return current; }
}
public void SetCurrent(string val)
{
current = val;
}
}
In the dynamicClass (TheClass) I keep a member variable of that type.
The full source for the script looks like the following:
using System;
using System.Reflection;
using Scripting;
using ScriptingObject;
namespace DynamicScript
{
public class TheScript : System.MarshalByRefObject,
Scripting.IRemoteInterface
{
// variable that keeps the instance of the scripting object
private ScriptingObject sys;
// Property that returns the scripting object
public virtual ScriptingObject. SysObject
{
get {return this.sys;}
}
// Constructor for the class
public TheScript()
{
// Create an instance of the scripting object
sys = new ScriptingObject();
}
public virtual object Invoke(string method, object[] parameters)
{
return this.GetType().InvokeMember(method,
System.Reflection.BindingFlags.InvokeMethod, null, this, parameters);
}
public virtual string Method1()
{
sys.SelectCurrent(sys.Current + "X");
return sys.Current;
}
public virtual string Method2(ScriptingObject obj)
{
obj.SelectCurrent(obj.Current + "X");
return obj.Current;
}
}
}
In my application, before calling Method1 I tried retrieving the sys
object using the property. When I try to execute:
ScriptingObject obj = (ScriptingObject) scripting.CallMethod
("get_Current", null);
I receive an exception stating that ScriptingObject must be marked
serializable. But if I do declare it serializable then a copy is
returned and not a reference, hence the following:
ScriptingObject obj = (ScriptingObject) scripting.CallMethod
("get_Current", null);
obj.SelectCurrent("Y");
string result = (string) scripting.CallMethod("Method1", null);
returns "X" and not "YX" as expected if both were dealing with the same
object.
Similarly, the following:
ScriptingObject newObject = new ScriptingObject();
newObject.Current = "Y";
string result = (string) scripting.CallMethod("Method2", new object[] {
newObject});
returns "YX", but if I inspect newObject, it still holds the value "Y".
Thanks,
Jeronimo Bertran