Skip to content

Instantly share code, notes, and snippets.

@toptensoftware
Last active October 19, 2016 04:38
Show Gist options
  • Select an option

  • Save toptensoftware/ed6cf10a5e9e4d0a7410567527913088 to your computer and use it in GitHub Desktop.

Select an option

Save toptensoftware/ed6cf10a5e9e4d0a7410567527913088 to your computer and use it in GitHub Desktop.
Converting Parameters using Reflection
// The parameters that will be passed to the C# code via reflection
List<object> csharpParameters = new List<object();
// Position of next parameter on the VM stack (+4 because the
// caller’s return address is also on the stack)
ushort vmStackPos = _machine.sp + 4;
// Convert all parameters
foreach (var pi in mi.GetParameters())
{
if (pi.ParameterType == typeof(ushort))
{
// Read 2 bytes from the stack
csharpParameters.Add(_machine.ReadWord(_machine.ss, vmStackPos));
vmStackPos += 2;
}
else if (pi.ParameterType == typeof(string))
{
// Read string pointer from the stack 
var stringPtr = _machine.ReadDWord(_machine.ss, vmStackPos));
vmStackPos += 4;
// Read the string from VM memory
string str = _machine.ReadString(stringPtr);
csharpParameters.Add(str);
}
}
// Call the C# function, passing parameters
var retv = mi.Invoke(this, csharpParameter.ToArray());
// Return value to VM
_machine.ax = (ushort)Convert.ChangeType(retv, typeof(ushort));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment