.net CLR, boost and mixed mode fun

Last week we tried to create a managed C++ DLL that includes another managed library and a library that is purely native. What made matters even more funky was, that the native library extensively made use of the boost library.

I haven’t been a great fan of that particular library (because it quite bloats your debug binaries, take ages to compile and introduces code that you are not in control of and that hardly anyone understands) but the code was there already, so what can you do 🙂

So first trial was to just make a DLL project that compiles with /clr Option and statically link the other two libraries.
Everything works fine, compile and link wise that is. But when you start your C# client application an exception pops up: “BadImageFileException” with hardly any additional information. Forum posts that one of the libs might be complied 64bit whilst the others were 32bit or something similar were in that case misleading, although above differences can also lead to that particular exception.

To cut a long story short, here the steps to take care of when trying to include boost library code into a mixed mode DLL:

  • In our scenario boost threads only work when linked dynamically, that is
    #include <boost/thread.hpp>
  • The second thing that we did in our CLR DLL was to split the 2 “sides” into 2 cpp files giving something like something_native.cpp and something_managed.cpp. In the native part we added references to the native libs with a construct like this:
    #pragma managed(push, off)
    #include <unmanaged_sublib.h> //unmanaged includes
    #pragma comment(lib...)
    #pragma managed(pop)

With above steps we were able to build a mixed mode DLL that delivers all the functionality provided by the two sublibraries, the managed (easy) and also the native library using boost*. Now I can enjoy my holidays 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *