[Python.NET] Embedded scripting

Sam Iredale gyrepin at techie.com
Thu Aug 5 20:31:26 CEST 2004


I'm trying to embed Python for application scripting in my C# solution.
I've managed to load the Python module form C#; but how do I get the
Python script to call back into the application? The "from MODULE import
CLASS" semantics throw an exception here; and I think it's because the
class being called is in the same process (not in a dll). 

Here's the test C# code:

using System;
using Python.Runtime;

namespace PyTest
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	public class PyTestClass
	{
		PyObject module = null;

		public PyTestClass()
		{
			PythonEngine.Initialize();
		}
		~PyTestClass()
		{
			PythonEngine.Finalize();
		}

		public void PyMessage()
		{
			Console.WriteLine("PyMessage() has been
called.");
		}

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			PyTestClass pyTest = new PyTestClass();

			try
			{
				if(!PythonEngine.IsInitialized)
					throw new
Exception("PythonEngine not initialized.");
				pyTest.module =
PythonEngine.ImportModule("PyTest");
			}
			catch(Exception e)
			{
				Console.WriteLine(e.Message);
				Console.Write(e.StackTrace);
			}
		}
	}
}

And the Python script:

from PyTest.PyTest import PyTestClass
def test():
   print "testing."
   PyTestClass.PyMessage()
test();


I know the embedding is working; because when the module is loaded, if I
comment out the import line and the call to the PyTestClass in the
script, the string "testing." is output to the console. But once I put
in the stuff that calls back into the C# code, it throws a
PythonException. Any ideas?

Thanks,
SI



More information about the PythonDotNet mailing list