Feeds:
Posts
Comments

Archive for May, 2011

This question was recently asked in the MSDN forums and answered by myself, and I am blogging it here so I have a page to link to if something similar gets asked again in that or some other forum. The OP had a C# caller that called a mixed-mode DLL’s method that took 3 arguments of type int%. This mixed-mode method then called a native function that took 3 arguments of type int* and modified all three of them. The OP was confused as to how to pass the int% values passed from C# to the native method. The central issue was that although int is a value type, int% is a tracking reference and needs to be pinned first. Once you do that, you just pass it to the native method. Example code snippet:

void nativefunc(int *p1, int *p2, int *p3)
{
  // . . .
}

void managedfunc([Out]int% mp1, [Out]int% mp2, [Out]int% mp3)
{
  pin_ptr<int> p1 = &mp1;
  pin_ptr<int> p2 = &mp2;
  pin_ptr<int> p3 = &mp3;

  nativefunc(p1, p2, p3);
}

Read Full Post »

This was recently asked in the Code Project Q/A forums, and while there were several responses posted, I think the following is succint and works well.

private static bool IsValidFlagValue<T>(int x) where T : struct
{
    int aggregate = Enum.GetValues(
      typeof(T)).Cast<int>().Aggregate((z, y) => z | y);
    return x <= aggregate && (aggregate & x) > 0;            
}

Note that it does not handle a case where the flag-enum has a 0-value. Here’s a version that does that too (a little less brief).

private static bool IsValidFlagValue<T>(int x) where T : struct
{
    var values = Enum.GetValues(typeof(T)).Cast<int>();
    if (x == 0 && values.Contains(0))
    {
        return true;
    }

    int aggregate = values.Aggregate((z, y) => z | y);
    return x <= aggregate && (aggregate & x) > 0;            
}

Read Full Post »

Follow

Get every new post delivered to your Inbox.