314
❘
CHAPTER 15
Using ironPython from other .net LangUages
// Display the result.
Console.WriteLine(“5 + 10 = {0}“, Result);
// Pause after running the test.
Console.WriteLine(“\r\nPress any key when ready...”);
Console.ReadKey();
}
This example builds on the example you saw in Chapter 14. In this case, the code begins by creating
a script engine. Think of this engine as a means to access
IPY.EXE
without actually loading
IPY.EXE
.
If you don’t really understand the
ScriptEngine
object,
Eng
, make sure you read through the theory
section in Chapter 14. What this code is showing you is the practical application of that theory.
Now that you have access to
Eng
, you can use it to perform various tasks. For example, you must tell
Eng
what scope to use when executing code, so the example creates a
ScriptScope
object,
Scope
. In
order to perform tasks, you must also have an
ObjectOperations
object,
Ops
. The example uses the
defaults provided for each of these objects. However, in a production application, you might decide to
change some properties to make the application execute faster or with better security.
At this point, you can execute the script. The act of executing the script using
Source.Execute()
loads the script into memory and compiles it in a form that the static application can use. The
Source.Execute()
method associates
Scope
with the execution environment. At this point, the
parameters for executing the script are set in stone — you can’t change them.
The script is in memory, but you can’t access any of its features just yet. The script contains a
DoCalculations
class that you access by calling
Scope.GetVariable()
to create
CalcObj
. The
code gains access to the class by creating an instance of it,
CalcObj
, using
Ops.Invoke()
. At this
point,
CalcObj
contains an instance of
DoCalculations()
in the IronPython module, but you can’t
use it directly. Remember that you must marshal data between C# and IronPython. In addition, C#
has to have a way to deal with the potential changes in the IronPython script.
In order to use the
DoAdd()
method in
DoCalculations()
, the static application must create an object
to hold a call-site cache, as explained in Chapter 14. To do this, the code calls
Ops.GetMember()
with
the instance of
DoCalculations()
,
CalcObj
, and the name of the method it wants to access,
DoAdd()
.
The result is the
AddMe
object.
This seems like a lot of work just to gain access to
DoAdd
, but you can finally use
AddMe
to perform
the addition. A call to
Ops.Invoke()
with
AddMe
and the arguments you want to use performs all
of the required marshaling for you. You must coerce the output to an
Int32
(something that C#
understands). Finally, the application outputs the result, as shown in Figure 15-3.
Do'stlaringiz bilan baham: |