1

I'm a C++ programming who was tapped to write a small application in Visual Basic. The application hosts an IronPython runtime and I am attempting to define some function in python and then call them from VB. I have written a simple test function in python

def test(): 
    print "Test was Called"

Then I use the iron python to create a ScriptSource from the python file. I am able to look up the "test" variable through object operations but I can not figure out how to call the object that. For example (in VB):

pyScope = engine.CreateScope()
pySource = engine.CreateSourceFromFile("C:\Some\File\path\test.py")
pySource.Execute(pyScope)
' Now I expect the function test() to be defined in pyScope
Dim tmp as Object
pyScope.TryGetVariable("test", tmp)

At this point in my code tmp is defined as an object of type PythonFunction. I can't figure out how to call this function.

tmp()

Is not valid VB syntax. I've gotten this far, now how do I perform this seemingly simple task?

Edit: By calling

 pyEngine.Operations.Invoke(tmp)

I am able to call the function and I see the expected output at stdout. I am still under the impression that there is some function-pointer-like type that I can cast objects of type PythonFunction to which will let me invoke temp directly without calling to the Python engine.

mjn12
  • 1,853
  • 3
  • 19
  • 27

2 Answers2

0

Not sure this will work, but try casting it to an Action type:

DirectCast(tmp, Action)()

Based on the comment, try this:

engine.ObjectOperations.Invoke(tmp, Nothing)
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • Unfortunately that does not work. I get an exception of "Unable to cast object of type 'IronPython.Runtime.PythonFunction' to type 'System.Action'." – mjn12 Apr 17 '12 at 13:45
  • Now we're getting somewhere - I have a type I can work with. Updating. – Joel Coehoorn Apr 17 '12 at 13:46
  • Ha, I just discovered that right before I commented on your post. From reading the documentation and looking at C# examples I feel like I should be able to cast tmp to a callable type. See http://www.voidspace.org.uk/ironpython/dark-corners.shtml#delegates-and-calltarget0 – mjn12 Apr 17 '12 at 13:51
0

VB in .NET 4 should have the same dynamic support as C#. According to http://msdn.microsoft.com/en-us/library/ee461504.aspx#Y5108 (near the bottom), you should be able to do:

Dim tmp As Object = scope.GetVariable("test")

... which is what you're already doing, so make sure you're targeting .NET 4.

If that doesn't work you should be able to cast it with the generic version of GetVariable:

Dim tmp As Action = scope.GetVariable(Of Action)("test")

Finally, you already discovered Invoke on ObjectOperations.

(You may need to tweak the syntax, since I don't know VB.)

Jeff Hardy
  • 7,632
  • 24
  • 24