using PERLEZHANDLE = System.IntPtr; class MyClass { [DllImport("PerlEz.dll")] private static extern PERLEZHANDLE PerlEzCreateOpt(string lpFileName, string lpOptions, string lpScriptOpts); [DllImport("PerlEz.dll")] private static extern int PerlEzCall1(PERLEZHANDLE hHandle, string lpFunction, [MarshalAs(UnmanagedType.LPStr)] StringBuilder lpBuffer, UInt32 dwBufSize, string lpFormat, IntPtr IntPtr1); // Callback Function public delegate string Callback(); static public string foo() { return "Hello C# World."; } [STAThread] static void Main(string[] args) { PERLEZHANDLE PerlHandle = PerlEzCreateOpt("test.pl", null, null); // Create a function pointer to the callback Callback cb = new Callback(foo); IntPtr fp = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(cb); // Invoke the perl function StringBuilder Response = new StringBuilder(1024); int ReturnCode = PerlEzCall1(PerlHandle, "test", Response, System.Convert.ToUInt32(Response.Capacity), "i", fp); if(ReturnCode == 5) Console.WriteLine("Exception!"); else Console.WriteLine("Response: " + Response.ToString()); } } #### #use strict; require DynaLoader; sub test { my ($a, $b, $c, $d) = @_; # Convert the SV into a CV (...I hope) my $code_ref = DynaLoader::dl_install_xsub("main::foo", $a); # An exception occurs on the next line. return "Hello Perl World." . $code_ref->(); }