Search code examples
c#reflectionexpression-treesunsafe

Calling unsafe method using expression trees


I need to call unsafe method that takes raw pointers.

For that I need to construct Expression that represents pointer to value represented by VariableExpression or ParameterExpression.

How to do that?


Solution

  • My usual approach to Expression stuff is to get the C# compiler to build the Expression for me, with its wonderful lambda-parsing ability, then inspect what it makes in the debugger. However, with the scenario you describe, we run into a problem almost straight away:

    New project, set 'Allow unsafe' on.

    Method that takes raw pointers:

    class MyClass
    {
        public unsafe int MyMethod(int* p)
        {
            return 0;
        }
    }
    

    Code that builds an expression:

    class Program
    {
        unsafe static void Main(string[] args)
        {
            var mi = typeof (MyClass).GetMethods().First(m => m.Name == "MyMethod");
    
            int q = 5;
    
            Expression<Func<MyClass, int, int>> expr = (c, i) => c.MyMethod(&i);
    
        }
    }
    

    My intent was to run this and see what expr looked like in the debugger; however, when I compiled I got

    error CS1944: An expression tree may not contain an unsafe pointer operation

    Reviewing the docs for this error, it looks like your "need to construct Expression that represents pointer to value" can never be satisfied:

    An expression tree may not contain an unsafe pointer operation

    Expression trees do not support pointer types because the Expression<TDelegate>.Compile method is only allowed to produce verifiable code. See comments. [there do not appear to be any comments!]

    To correct this error

    • Do not use pointer types when you are trying to create an expression tree.