开发者

Enum of GUID's/Guid interop

开发者 https://www.devze.com 2023-02-19 07:24 出处:网络
I\'m doing some interop and need to pass some GUID\'s. Is there a way to add a GUID attribute to an enum value and when it is marshalled it has the appropriate value?

I'm doing some interop and need to pass some GUID's. Is there a way to add a GUID attribute to an enum value and when it is marshalled it has the appropriate value?

Basically I'm trying to convert the code

#if !defined( STATIC_KSDATAFORMAT_SUBTYPE_PCM )
#define STATIC_KSDATAFORMAT_SUBTYPE_PCM\
    DEFINE_WAVEFORMATEX_GUID(WAVE_FORMAT_PCM)
DEFINE_GUIDSTRUCT("00000001-0000-0010-8000-00aa00389b71", KSDATAFORMAT_SUBTYPE_PCM);
#define KSDATAFORMAT_SUBTYPE_PCM DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_PCM)
#endif

(and several other similar ones)

and use them in an enum so I can specify the appropriate subtype format easily. Obviously I could probably just use a dictionary or some other similar method but I would like to make it as transparent as possible.

It would be nice to do something like

enum MyGuids : Guid
{
  Guid1 = GUID("...") or just "..."
}

I can use a class/struct instead

开发者_运维知识库
static class MyGuids
{
    public static Guid flag1 = new Guid("9ED54F84-A89D-4fcd-A854-44251E925F09");
}

But the only problem here is there is no way to relate the Guid in unmanaged structure to this class. It's specified as Guid and if I replaced it with MyGuids then it won't be a Guid any more. e.g., I lose type safety since any guid can end up in the field and not just the ones from MyGuid.

Any ideas?


Guids are structures in .NET, they are too large to fit in a simple value type by a factor of two. Sounds to me that you need a structure member initialized. That's going to need an assignment statement in your code. The const will work just fine for this. There is otherwise no way to get the compiler to do it automatically.

  var sound = new foo();
  sound.waveFormat = MyGuids.flag1;
  // etc..


How about something like this?

void Main()
{
    var dog = MyValues.Dog.ToId();  
    var cat = MyValues.Cat.ToId();  
    var bird = MyValues.Bird.ToId();    
}

public enum MyValues
{ 
    Dog,
    Cat,
    Bird
}

public static class Functions
{
    public static Guid ToId(this MyValues value)
    {
        switch (value)
        {
            case MyValues.Dog:
                return Guid.Parse("6d139d6a-2bfa-466d-a9a5-c6e82f9abf51");
            case MyValues.Cat:
                return Guid.Parse("AA139d6a-2bfa-466d-a9a5-c6e82f9abf51");
            case MyValues.Bird:
                return Guid.Parse("BB139d6a-2bfa-466d-a9a5-c6e82f9abf51");
            default:
                throw new InvalidDataException();
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消