Monthly Archives: January 2012

“Nebuchadnezzar” or “How to avoid the UNSAFE keyword using an unmanaged C++ DLL from C#”

This post is a sequel of “Escaping the matrix”. Check it out before you read on.

* * *

Now we’re there. FREE.
But the UNSAFE Keyword kinda sucks, does it?

Well, normally I’d give you the advice to: “Take a risk, dud.”

But in this case there’s indeed someone out there to save our butt… in a morbidly beautiful ship called Nebuchadnezzar.

Nebuchadnezzar (Source: DeviantArt, Cold-Levian)

Marshalling, that ship is.
(Don’t you ADORE how I’m using these analogies?)

It’s morbid character comes from the fact that it’s only quick in very basic cases, as in the example given. (Swiss Ephemeris only uses very basic data types in its interface… which is wonderful.)

To use an unmanaged C++ DLL from C# without switching to the unsafe mode, do the following:

1. Remove all the UNSAFE keywords from the code. (You guessed that, didn’t you?)

2. Marshal every string as a StringBuilder.

[DllImport(@"C:\somepath\swedll32.dll")]
static extern void 
swe_set_ephe_path([MarshalAs(UnmanagedType.LPTStr)] StringBuilder path);

public void SetEphemerisPath()
{
  StringBuilder ephemerisTablesPath = 
    new StringBuilder(@"C:\Users\Administrator\Desktop\sweph\ephe");

  swe_set_ephe_path(ephemerisTablesPath);
}

3. Replace pointers with references using the ref-Keyword.

[DllImport(@"C:\somepath\swedll32.dll", 
CallingConvention = CallingConvention.StdCall)]
static extern int swe_calc_ut([...], ref double xx, [...]);

4. Make readable function names.

public int CalculatePlanetOrOtherBody([...], double xx, [...]){
  swe_calc_ut([...], ref xx, [...]);
}

And now go have some fun 😀


Protected: Building site photos (deprived from the public due to really weird traffic increase – just mail me for the pwd)

This content is password protected. To view it please enter your password below:


Knockdown

My summer and autumn of 2011 were totally taken in by my sister’s project of tearing down and reconstructing a huge part of our parental house.

Finally getting it done was a huge relief. Parts of the house were so decayed that most people would not believe me that I spent the first ten years of my life actually residing in that house.

A few days before the final demolition, I took some pictures. There were tears in my eyes.

This slideshow requires JavaScript.

These were really moving moments to me. This was NOT at all about something as banal as architecture.
It was about making peace and saying goodbye to my childhood. For good.