[IronPython] Hosting: Delegates from Ironpython to C#

Tim Riley riltim at gmail.com
Wed Aug 29 19:09:40 PDT 2007


I'm embedding IronPython in a C# dll that is hosted inside a program
called AutoCAD. In order to register commands in AutoCAD from .NET I
need to P/Invoke a C function inside a .dll. I can do this fairly easy
from C# but I can't figure out the right way to call my C# wrapper
from IronPython to have it register the command. I have perused the
hosting docs for 1.1 and haven't been able to come up with a solution
that works. Here is my C# code. I either want to call the PyRegCmds
void or the PythonRegister void.  Both of which expect a delegate.for
example if I had a python function like:

def test1:
    print "This is a test".

I can't figure out how to map test to the delegate required in the code below.
Note: I can call this from C# fine. See :static public void test().

Can anyone give me any pointers? It would be greatly appreciated.


code:

using System ;
using System.Runtime.InteropServices;
using Autodesk.AutoCAD.Runtime ;
using Autodesk.AutoCAD.EditorInput;

namespace PyAcadDotNet
{
	/// <summary>
	/// PyAcadCmd Class:
	/// Used to register commands on the AutoCAD command stack.
	/// </summary>
	public class PyAcadCmd
	{
		public PyAcadCmd()
		{
		}
		public delegate void CmdDelegate();

		/// <summary>
		/// RegPyAcadCmd:
		/// Registers a delegate (callback) with the AutoCAD command string
		/// on the command stack.
		/// </summary>
        [DllImport("PyRegCmd.dll",
			 CallingConvention=CallingConvention.Cdecl,CharSet = CharSet.Unicode,
			 EntryPoint = "?RegPyCmd@@YAXPB_W0HP6AXXZ at Z")]
		public static extern void RegPyCmd(
			string cmd_group,
			string cmd_name,
			Autodesk.AutoCAD.Runtime.CommandFlags cmd_flags,
			[MarshalAs(UnmanagedType.FunctionPtr)] PyAcadCmd.CmdDelegate cmd_delegate);


        public static void PythonRegister(string CommandName,
CmdDelegate FuncPointer, CommandFlags flags)
        {
            RegPyCmd("_pycmds", CommandName, flags, FuncPointer);
        }

        //testing stuff
        public static void testcommand()
        {
            Editor ed =
Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("\ncb1 delegate seems to work!\n");
        }
        [CommandMethod("regcmds")]
        static public void test() // This method can have any name
        {
            CmdDelegate cb1 = new CmdDelegate(PyAcadCmd.testcommand);
            PythonRegister("testcommand", cb1, CommandFlags.Session);
        }
	}


}


More information about the Users mailing list