“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 😀

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: