views:

429

answers:

1

Hi to all!

I have problem with get data from vbscript in C# console application. I just write below code:

        int[] i = new int[3] { 1, 2, 3 };
        string msg = "";
        object[] myParam = { msg , i};
        MSScriptControl.ScriptControlClass sc = new MSScriptControl.ScriptControlClass();            
        sc.Language = "VBScript";
        sc.AddCode("Sub Test(ByRef msg, ByRef aryI)" + Environment.NewLine + 
                    "  msg = \"234\"" + Environment.NewLine +                        
                    "End Sub");
        sc.Run("Test", ref myParam);

I want to get msg modified string after call Run method, but it does not work anymore(not any change)

Could you please help to me ?

Thanks in advance

+1  A: 

You will have to use Eval function or something similar that will return you the value back to you.

int[] i = new int[3] { 1, 2, 3 };        
string msg = "";        
object[] myParam = { msg , i};        
MSScriptControl.ScriptControlClass sc 
   = new MSScriptControl.ScriptControlClass();
sc.Language = "VBScript";
sc.AddCode("Function Test(ByRef msg, ByRef aryI) as String" + 
Environment.NewLine +  "  msg = \"234\"" + 
Environment.NewLine +  "  Test = msg" + // this Test=msg is a return statement
Environment.NewLine + "End Function");

msg = (string)sc.Run("Test", ref myParam);
or 
msg = (string)sc.Eval("Test",ref myParam);

I dont know which one of above will work correcly but there will be something similar.

You are passing a variable to Script, in instance of Script only, the variable is used as Reference, but when C# passes the variable in sc.Run method it passes it as only value, not reference.

There is no way you can retrive value back which is ByRef in script.

Alternative way is to pass entire object.

[ComVisible(true)]
public class VBScriptObjects{
      public string Property1 {get;set;}
      public string Property2 {get;set;}
}


VBScriptObjects obj = new VBScriptObjects();

sc.AddObject( "myObj", obj , false);
sc.Run("myObj.Property1 = 'Testing'");

obj.Property1 <-- this should have a new value now..

Making class ComVisible, can let you access and change the properties through vbscript.

Akash Kava
Many thanks for quick reply. but I need to change more than one parameter and return all. With Function we can get only one.
Hamid
Please check alternate version I have just added.
Akash Kava
Dear Akash Kava, I do it, but when run application, get "Specified cast is not valid." exception on line sc.AddObject( "myObj", obj , false);Note: I just set comvisible(true) for class and also project, but get same error. Could you please help me ?
Hamid