Is it possible to expose a C# Enum to COM Interop callers, and if so, how?

感情迁移 提交于 2019-12-06 18:30:02

问题


I have a managed assembly that gets called via COM Interop. Like a VBScript client, a Perl client, and so on.

The classes are decorated with

[ClassInterface(ClassInterfaceType.AutoDual)]
[GuidAttribute("ebc25cf6-9120-4283-b972-0e5520d0000E")]
[ComVisible(true)]

Then of course I do the regasm thing, and all the methods work just fine.

But there are also enum types in the assembly. I'd like to use symbolic names COM applications, for the enum values.

How do I expose the enums via COM interop? Do I just need to add these attributes?

[GuidAttribute("ebc25cf6-9120-4283-b972-0e5520d0000E")]
[ComVisible(true)]

And then, how do I reference those symbolic names in VBScript? I don't see the enum types in OleView. (Should I?) I see all the other types in OleView.


回答1:


VBScript and other late-bound clients use IDispatch to call methods on objects. As such, these languages don't have access to type information in the typelib -- they just create an object from a GUID, get an IDispatch pointer back, and start calling methods by name.

I'm unsure of the COM interop part of the question, but even if the enums did show in OleView, you wouldn't be able to use them directly.

However, if you are able to publish the enums in the typelib, I wrote a tool eons ago that can generate a script file (vbs or js) containing all the enums from a typelib as constants.

See here: http://www.kontrollbehov.com/tools/tlb2const/




回答2:


My (so far only) .NET assembly that I made COM-visible also had an enum type, which showed up just fine in OleView. I had the whole library be COM-visible so

[ComVisible(true)]

was not necessary. Is your enum type public?

One thing that happened was that the different enumerations were 'prefixed' with 'enum type name'_:

public enum DataType
{
    INT32,
    FLOAT64,
    INT8
}

turned into:

typedef [...]
enum {
    DataType_INT32 = 0,
    DataType_FLOAT64 = 1,
    DataType_INT8 = 2
} DataType;

in the type library.




回答3:


I know this is a very old thread, but I'll add my 2 cents for future explorers. When I define an enum in C# I decorate it with [Guid(...), ComVisible(true)] not GuidAttribute.
For example:

[Guid("28637488-C6B3-44b6-8621-867441284B51"), ComVisible(true)]
public enum myEnum
{
    first,
    second,
    third,
    fourth
}

Then the enumeration would be available in VB6 as myEnum_first, myEnum_second and so forth.

You can include the assignment of key values in that list as well, so first = 1 would be valid in the enumeration.



来源:https://stackoverflow.com/questions/1276442/is-it-possible-to-expose-a-c-sharp-enum-to-com-interop-callers-and-if-so-how

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!