문제

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 IntPtrs in safe code, so it should also be no problem to use them in expression trees.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top