Posts

Shutting Down Windows from C++

Windows can be programmatically shutdown using the ExitWindowsEx() Win32 function.  However it turns out that the trick to getting it to work is to first grant shutdown priviliges to the calling process via some rather ugly security functions – this type of faffing around can never me remembered so I will post some sample code here in the hopes that it might help me (in the future) or maybe someone else:

Native Lambda Expressions in C++? Yes Please!!

Today I came across a situation which brought it home to me again how (in my opinion) C++ could desperately do with native lambda function support.  The standard library has introduced a load of great algorithms, but providing predicates and the like to them is a real pain – and I think that because of this people tend to stick to hand rolling good old-fashioned loops.

 

Consider replacing a few different characters in a std::string with a single given character, e.g., replace the characters ‘$’ and ‘|’ with ‘_’.  A good way of doing this in C++ would be to use the boost regular expression library, but we could also use the std::replace_if() algorithm.  All we have to do to use this algorithm is to privide a predicate that indicates if a given character should be replaced or not (say called is_bad_char()), then we do something like:

 

 Looks easy enough, and it’s nice and concise.  All we have to do now is define is_bad_char(), something like:

I mean! what a pallava!  that’s quite a mouthful, would you really be bothered? You would have a loop coded in just the time it took to start to remember that syntax, never mind the typing. it also looks terribly inelegant.

 

Now when native lambda support arrvies we will be able to do something like this instead:

That’s much better… but not available yet, we will just have to wait for c++0x to arrive. In the mean time I will just have to use lambdas in the many other languages that support them and pine when using C++.

Implicit Cast of Lambda Expression to Custom Class in C# 3.0?

We hit a little speed bump in our work with parameter-less lambdas – we wanted to be able to assign them to objects of a custom class via an implicit cast, this is very important to our cunning plan…

 

To illustrate this consider the following class that just encapsulates a 0-arity delegate Func<T>:

Now, because we have specified an implicit cast for: Func<T> -> RuleProp<T>, it would seem  that we should be able to do the following:

But this gives us a compiler error, can’t convert lambda to Fun<T> as it’s not a delegate!!  Looking at the C# specification it seems that if more than one implicit conversion is required, the C# compiler will only do one.  In this case 2 conversions are required:

 

Lambda Expression -> Func<T> -> RuleProp<T>

 

And so the compiler can’t handle it.  If we provide an explicit cast to Func<T> it compiles OK:

 

 

But this is really ugly as the type must be provided each time.  A workaround was suggested in this article:

 

http://www.interact-sw.co.uk/iangblog/2008/03/17/lambda-inference

 

We provide an ‘adaptor’ function which encourages a cast from Lambda -> Func<T>, and the implicit cast from Func<T> to RuleProp<T> will handle the rest, we can use it like this:

 

This is much nicer than the explicit cast as no type needs to be specified!  Here is the function, it just take,s and directly returns a delegate – resulting in just the conversion that we need!

 

 

So although it is not as nice as directly assigning a lambda to RuleProp<T> it’s a grand workaround and will do nicely for the time being – thanks to all at the C# MSDN forum for their help!

Programatically Converting a Literal into an equivalent Lambda Expression in c#3.0

As part of a project that we are working on at the moment  we need a way of converting a literal or constant into a lambda expression which when evaluated will yield the original literal value (in c#).  This must work in the same way for multiple types.

 

For example given the literal string “hello” we need to programmatically create the lambda

 

() => “hello”

 

and for the boolean true we want to create:

 

() => true

 

etc.

 

This can be achieved by creating an appropriate expression tree and then compiling it into a lambda expression, and as we want this to work for different types we wrap all of this into a generic function like the following:

 

        static public Func<T> ToLambda<T>(T val)
        {
            ConstantExpression body = Expression.Constant(val);
            LambdaExpression exp = Expression.Lambda<Func<T>>(body, null);

 

            return (Func<T>)exp.Compile();
        }

 

The function takes the value in question as type T and returns a parameter-less delegate of return type T.  It uses the passed value to create a ConstantExpression, and then uses it to create a LambdaExpression, as the required lambda has no paramters it passes ‘null’ into the constructor’s second parameter.  Now all that is left is to compile the LambdaExpression, this creates and returns the required delegate which is then returned.

 

The following code shows the lambda generator in action:

 

        static public void TestLiteralToLambda()
        {
            // Create the Lambda from literal
            var boolLambda = ToLambda(true);
            // Evaluate the lambda..
            bool boolVal = boolLambda();
            // and, log out some info
            Console.WriteLine(“Lambda evaluates to – {0}”, boolVal);

 

            var stringLambda = ToLambda(“Rainy day in Dublin”);
            string stringVal = stringLambda();
            Console.WriteLine(“Lambda evaluates to – {0}”, stringVal);

 

            var doubleLambda = ToLambda(3.14159);
            double doubleVal = doubleLambda();
            Console.WriteLine(“Lambda evaluates to – {0}”, doubleVal);          ?
        }

 

So far, so good.  Although this might seem a little strange and vaguely useless, what it allows us to do is to treat literals and lambdas of the same type in exactly the same way.

 

Specifically what we want to be able to do is to define ‘super properties’ on objects whose values when queried are either regular values (as normal) or are the result of evaluating a rule, this rule being provided as a lambda expression.  When the property’s value is set the programmer either provides a value (literal or constant) or a rule (lambda expression).

 

Further details on the exact makeup of these ‘super properties’ elude us at the moment, more later…