IamIC
IamIC

Reputation: 18269

Translating unmanaged C++ code to managed C++ for calling from C#

I have some C# code that requires extensive binary manipulation, so I wrote an unmanaged C++ method to replace one of the C# methods. To my shock, is was 10 X slower. I ran a profile, and discovered the slowness comes from the overhead of calling the external method, not the method itself.

So I thought that if I write the method in managed C++, I will loose the overhead of the call, but still have the speed of C++. First, is this assumption valid?

Here is my unmanaged C++ code:

#include "stdafx.h";

unsigned __int32 _stdcall LSB_i32(unsigned __int32 x)
{
    DWORD result;
    _BitScanForward(&result, x);
    return (unsigned __int32)result;
}

Here is my C# code:

public static partial class Binary
{
    [DllImport(@"CPP.dll")]
    public static extern int LSB_i32(int value);
}

Am I doing anything wrong here?

How do I translate the above to managed C++? I did some browsing on this, but because I am unfamiliar with managed C++, I didn't get far.

Upvotes: 2

Views: 311

Answers (2)

Codo
Codo

Reputation: 79033

You can try if a pure C# implementation is faster:

static int lzc(int x)
{
    x |= (x >> 1);
    x |= (x >> 2);
    x |= (x >> 4);
    x |= (x >> 8);
    x |= (x >> 16);

    x = x - ((x >> 1) & 0x55555555);
    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
    x = (x + (x >> 4)) & 0x0f0f0f0f;
    x = x + (x >> 8);
    x = x + (x >> 16);
    return 32 - (x & 0x0000003f);
}

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

You could leave the unmanaged method but you should not call it very often from managed code. For example if you are calling the unmanaged method in a tight loop then the overhead of marshaling between managed and unmanaged code will be enormous. So you could try putting this loop inside the unmanaged code so that you perform only a single call to the method. Then you will pay the marshaling price only once and the whole heavylifting will be done in unmanaged code.

As far as converting it to managed C++ is concerned, I highly doubt this would bring you anything better than what you started with (i.e. fully managed C# code).

Upvotes: 2

Related Questions