简体   繁体   中英

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?

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.

I think AakashM's answer is useful (the idea to leverage the compiler to build your expression trees) so there is no need to repeat it.

However, I don't think it is completely impossible to use pointers: If you do not dereference the pointers, you can pass them around stored in an IntPtr . You can use and pass around IntPtr s in safe code, so it should also be no problem to use them in expression trees.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM