Category Archives: .NET

.NET DLLs Loaded Twice

If, like me, you’re still squeezing yourself into 32-bit Windows processes, you’re probably, also like me, constantly keeping an eye on the virtual address space usage of your application. If you happen to have used something like vmmap to take a peek at your memory contents, maybe you’ve noticed something strange with some .NET assemblies: they’re loaded twice! What’s going on…?
Continue reading .NET DLLs Loaded Twice

Kinect SDK with F#

Just what do you think you're doing, Dave?
Just what do you think you're doing, Dave?
I finally got around to taking a look at the Kinect SDK the other day, partly because I was interested to see how the API looked from F#. Unfortunately getting it going turned out to be more of a pain than I was expecting.

The first bit was easy: I’m “lucky” enough to have one of the older Xboxes, which meant I’d had to get a Kinect with separate power, which is the one required by the SDK. Now all I needed was a Windows machine to develop on.
Continue reading Kinect SDK with F#

Am I being called from DllMain?

Lock; literal images 'r' us
Lock; literal images 'r' us
While Googling for an obscure Windows function the other day, I came across this fantastically useful repository of undocumented WinAPI functions, put together by Geoff Chappell. I’m not sure how I hadn’t discovered it before.

One of the functions that immediately caught my eye was LdrLockLoaderLock. I’d previously spent quite a few frustrating hours trying to figure out how to determine whether some code was being executed from DllMain, i.e. while in the loader lock, so I could avoid doing anything dodgy – or indeed, anything at all.

The case I was looking at was some logging library code that was used, amongst other things, to record the fact that DLLs were being unloaded. Unfortunately when this was called from DllMain, it sometimes caused a deadlock, for all the reasons we already know about. The library code was called from lots of DLLs, so it wasn’t feasible to fix all of the call sites, instead I had to make the logging a no-op when it’s not safe.
Continue reading Am I being called from DllMain?

F# Async: Plays well with others?

OK, quick Async pop quiz: How long does the run function below take to execute?

module Test = 
    let work i = 
        async { 
            System.Threading.Thread.Sleep(500) 
            return i+1 
        }
    let run _ = 
        [1..1000] |> List.map work 
        |> Async.Parallel 
        |> Async.RunSynchronously

(Waits for people to start FSI and paste in the code…)

My guess would’ve been something just over 500ms; each of the 1000 async tasks would surely sleep in parallel, and then the operation itself is trivial. The additional elapsed time would be dominated by the overhead of thread management, and depend on the number of threads that can physically run in parallel (I’m using an 8-core machine). But still, something close to 500ms…

The actual result? 28000ms. Yes, you read that right: 28 seconds. What on earth did we do wrong?
Continue reading F# Async: Plays well with others?

Mixing it up: when F# meets C#

Simples?
Simples?
If it were a perfect world, we’d all exist in a happy little bubble of our favourite programming language and you’d never have to worry about the nasty details of interacting with something written by – gasp – someone else in a – double-gasp – different language. But unfortunately that’s precisely what we have to do all the time. And that means that one day all of your fancy-pants algorithmic, highly parallel, functionally pure F# code is going to meet the world of “enterprise” C# development head-on.

Of course the idiomatic way to avoid problems at the boundary between your F# code and the outside world is to ensure that you only expose a small set of compatible types. This works pretty well if your clients are also .NET languages. For instance you can do things like exposing your collections as seq, rather than say, a native F# list, and this will mean your collections can be consumed as IEnumerable. The only problem is it means you’ve got the added burden of maintaining this mapping layer, because you’ll no doubt want to use the F# “native” types internally.

So, what options do we have if some of our F# types happen to leak into our public API? Luckily, lots. Let’s take a look at how some of the common F# constructs can be called from C#.
Continue reading Mixing it up: when F# meets C#

Beginning F#: Positive Discrimination

(or “Discriminated unions for dummies like me”, or “Tagged unions for the rest of us”)

Discriminated unions are one of those things in the lexicon of functional programming that can often sound baffling to “outsiders”; it’s almost up there with monads and currying. But in practice they’re simple and incredibly useful. I thought I’d try and show a concrete example of where they can be used in a way which is more powerful and robust than the equivalent OO approach.
Continue reading Beginning F#: Positive Discrimination

Quick post: Using Mono.Cecil and F# to get assembly dependencies

One of the tools I use a lot when doing C++ development and debugging is “dependency walker”; an app that displays all the static dependencies of an executable. These are dependencies created by referencing functions from an import library (.lib file) at compile time. If any of the imported DLLs are missing at run-time, the executable will fail to load, normally with error 2: file not found. Obviously pretty disastrous in production. The .NET equivalent is the binding failure. You can track down what went wrong at runtime using fuslogvw, but I’ve often wished for a tool like ‘depends’ to work out up-front what dependencies are required. Luckily because assemblies includes a list of dependent libraries in the form of a manifest this information can be accessed using reflection.

Mono-gorilla-aqua.100pxI’m a big fan of the Mono.Cecil library for doing reflection (and more!) with .NET. I’ve had issues in the past where the built-in .NET reflection (using Assembly.ReflectionOnlyLoad) attempts to load dependent libraries as you iterate over exposed types, even though it’s not supposed to (unfortunately I don’t have a repro to hand). This makes it very difficult to work on an assembly without having all of its dependencies available. Cecil doesn’t have this problem because it accesses the assembly in a lower-level way.
Continue reading Quick post: Using Mono.Cecil and F# to get assembly dependencies

Public static fields gone from F# 2.0

There have been quite a few changes in F# version 2.0, which shipped as the first “official” version of the language as part of Visual Studio 2010. Most of the changes are detailed in various release notes on Don Syme’s blog and other places, but unfortunately one of the more significant changes passed me by, and turned out to be quite significant in the context of WPF development: public static fields are no longer supported. But what does this mean?

The change

The change itself is simple: static fields can no longer be public. Static fields can still be created, but they must be private.

In pre-2.0 versions of F# it was possible to declare a static field on a type like this:

type MyType() =
    []
    static val mutable public MyProperty : int

Resulting in a type containing a static field, as you’d expect:

    .field public static int32 MyProperty

The code now generates the compiler error:

error FS0881: Static 'val' fields in types must be mutable, private and marked with the '[<DefaultValue>]' attribute. They are initialized to the 'null' or 'zero' value for their type. Consider also using a 'static let mutable' binding in a class type.

Notice that there are already some gnarly aspects to the definition of the property; notably the use of the [<DefaultValue>] attribute, which indicates that the field is un-initialized. This gives us a hint that there might be some inherent problems.

Why do we even need them?

In a word or three: WPF dependency properties.

The recommended way of implementing dependency properties in other .NET languages is to use public static fields, e.g. in C#:

    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register( 
          "MyProperty", typeof(int), typeof(MyType)); 

This is one of the few places where C# is terser than F#. Here we can declare and define the value in one line (ish), whereas F# requires a separate declaration of the field (as above) then initialisation in the static constructor (static do).

Why was it removed?

I got the answer from the horse’s mouth. Don Syme said that:

We deliberately removed the ability to create public static fields in Beta2/RC, because of issues associated with initialization of the fields (i.e. ensuring the “static do” bindings are run correctly, and if they are run, then they are run for the whole file, in the right order, with no deadlocks or uninitialized access when initialization occurs from multiple threads).

You can imagine how this would be a problem; there would need to be a way of ensuring that whichever static field was accessed it caused the static constructor to run, which may itself access static fields. All pretty nasty. In fact, Don mentioned that C# suffers from much the same synchronisation issues, but just tends to be used in a way that means it’s less likely to be noticed!

The alternative

At least in theory it’s possible to create a type that uses static properties rather than static fields to store its registered DependencyProperty information.

type Foo () =
    inherit FrameworkElement()
    static mutable private _myPropertyInternal : DependencyProperty 
    static member this.MyProperty with get () = _myPropertyInternal

Whether or not this works depends very much on how calling code accesses DependencyProperty information. If it uses reflection to access the field directly it will obviously fail. But if it uses a more robust/flexible method then it should be OK. Empirically it seems that the WPF framework code itself does the latter, for instance, when it’s instantiating objects from XAML, and it works properly independently of how it’s implemented.

The conclusion

So the conclusion is “wontfix”: the behaviour is by design. Unfortunately it has the effect that it’s no longer possible to create a type with an identical IL “signature” in both F# and C#. It seems a bit of a shame, but I guess the trade-off is that we’re protected against insiduous initialisation issues, so it will probably turn out to be the right thing in the long term.

Minilight renderer in F#

Cornell Box in the evening
Cornell Box in the evening
I’m a sucker for eye-candy, and the other day I came across the beautifully lit renders produced by Minilight. It’s a nice, minimal implementation of a global illumination renderer that’s been ported to a wide variety of different languages from C to ActionScript. So of course, I couldn’t resist trying to implement it in F#.
Continue reading Minilight renderer in F#

.NET 4.0 Type Equivalence causes BadImageFormatException

I recently discovered a nasty backward compatibility problem with the new type equivalence feature in .NET 4.0. Luckily it’s relatively difficult to hit it if you’re in a pure-C# environment, but if you happen to generate any assemblies directly using IL, you should watch out. Read on for all the gory details.
Continue reading .NET 4.0 Type Equivalence causes BadImageFormatException