Blog Closed

This blog has moved to Github. This page will not be updated and is not open for comments. Please go to the new site for updated content.

Saturday, April 10, 2010

Parrot in C#

Here's a little bit of proof-of-concept code that is going to interest a few people:
using System;
using System.Text;
using System.Runtime.InteropServices;

public static class Program {
    [DllImport("parrot")]
    private static extern System.IntPtr Parrot_new(System.IntPtr parent);

    [DllImport("parrot")]
    private static extern void Parrot_destroy(System.IntPtr interp);

    [DllImport("parrot", CharSet=CharSet.Ansi)]
    private static extern System.IntPtr Parrot_new_string(System.IntPtr interp,
        string text, int length, System.IntPtr whatever, int whatever2);

    [DllImport("parrot", CharSet=CharSet.Ansi)]
    private static extern System.IntPtr Parrot_compile_string(System.IntPtr interp,
        System.IntPtr compiler_name, string code, StringBuilder errmsg);

    [DllImport("parrot", CharSet=CharSet.Ansi)]
    private static extern void Parrot_ext_call(System.IntPtr interp,
        System.IntPtr sub, string sig);

    public static void Main(string[] args) {
        Console.WriteLine("Hello World from C#");

        System.IntPtr interp = Parrot_new(System.IntPtr.Zero);
        System.IntPtr pir = Parrot_new_string(interp, "PIR", 3, System.IntPtr.Zero, 0);
        System.IntPtr sub = Parrot_compile_string(interp, pir, @"
            .sub 'foo'
                say 'Hello from PIR'
            .end",
            new StringBuilder(256)
        );

        Parrot_ext_call(interp, sub, "->");
        Parrot_destroy(interp);

        Console.WriteLine("Hello again from C#");
    }
}
I've been kicking around the idea of starting a project to do full bindings between Parrot and .NET. I'm not sure that I'm ready to take on a new project, especially not one of that magnitude, but it's fun to think about.

I've got some more code examples for this that I'm putting together. Some of them can be pretty messy, especially when we talk about marshalling data between Parrot's various structures and C# code. However, I think it should be very possible to wrap all that messiness inside a series of nice, clean abstractions. It would be especially nice if we could get some scripts to parse through the embedding and extending function lists and generate the C# extern declarations automatically. With those, we can write some nice wrapper classes around the raw functions.

I'm sure I'll have more to write about this in the days ahead.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.