Category Archives: Coding

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


“Escaping the matrix” or “How to use the Win32 Swiss Ephemeris DLL from C#/.NET”

1:00 AM. Sleepless. Pondering. Up for dill pickles.

Repeatedly, I’m experiencing vivid symptoms of progressive intellectual pregnancy.
And it’s true. I’m bearing the idea of creating an astrological tool of my own, so I’d like to share the birth experience with you.
Well, at least the pains. ^^

Recently, I found a very extensive code library for computing planet positions. It’s called Swiss Ephemeris and it’s available right here.

The library is written in one of my favorite programming languages, namely C++.
Ohhh yes. Good old C++. No frills, just beauty. ROAR.

In spite of all the love for platform independent low-level languages and puristic coding style, I’d like to create a flashy front-end for my tool, so I’m gonna use C# on the .NET platform with loads and loads of pretty flashy *bling-bling* WPF functionality *bling-bling*.

Like the idea?
Yes? Come closer, then. All we need to do is escape “the matrix”. The cozy, safe environment of the .NET virtual machine, that is.

The Matrix (Source: DeviantArt, mrfu709851)

The first step outside of the matrix is to declare C# function wrappers which specify the entry points of the Win32 library:

        [DllImport("swedll32.dll")]
        static extern void swe_set_ephe_path(char* path);

The second step is to declare an unsafe class that contains all the methods which encapsulate all of the extern function calls:

    public unsafe class SwissEphemerisWrapper
    {
      public void SetEphemerisPath();
      ...
    }

The third step is to create a fixed scope if we need to pass parameters outside of the matrix:

        public void SetEphemerisPath()
        {
            fixed (char* path = ".\\sweph\\ephe")
            {
                swe_set_ephe_path(path);
            }
        }

Done. Took the red pill.

P.S.:
Read the Disclaimer, if you dare.