I think my question title is a bit confusing, so let me clarify. For my purposes, I'm applying a MarshalAsAttribute to parameters and return types.
(Note: Initially I didn't think this was working at all, but this question here lead me to post this question: System.Reflection.Emit - How to add attribute to return type definition?)
So let's say I'm dynamically creating a delegate type for a method with this signature:
[return: MarshalAs(UnmanagedType.I1)]
internal static extern Boolean SomeFunction([MarshalAs(UnmanagedType.LPStr)] string argument);
With code similar to the following, I can do this fine both for the function arguments and for the return type (note I'm omitting a bunch here for brevity):
var currentParameterAttributeBuilder = methodBuilder.DefineParameter(parameterPosition, currentParameterAttributes,
parameterName);
var attributeParams = new Type[] { typeof(UnmanagedType) };
var attributeConstructorInfo = typeof(MarshalAsAttribute).GetConstructor(attributeParams);
var customParameterAttribute = new CustomAttributeBuilder(attributeConstructorInfo, new object[] { currentArgument.MarshallingType });
currentParameterAttributeBuilder.SetCustomAttribute(customParameterAttribute);
However, when I go to check via reflection that the attributes exist, such as in the following:
// This works and retrieves the MarshalAs attribute
var argumentCustomAttributes = param.GetCustomAttributes(typeof(MarshalAsAttribute), false);
// This doesn't work; it doesn't 'see' the MarshalAs attribute
var returnCustomAttributes = type.GetMethod("Invoke").ReturnType.GetCustomAttributes(typeof(MarshalAsAttribute), false);
So basically, the attribute for the return type can't be viewed via reflection, but it is in fact applied, as seen in this .NET Reflector screenshot (this signature differs from above but demonstrates my point):
example image <-- I don't have enough reputation to embed images, sorry.
I'm just curious if anyone knows why this is, as I spent quite a bit of time struggling with it before I stumbled across that other post and realized it was actually being applied correctly. Hopefully I've formatted this correctly; it's my first time posting.
Aucun commentaire:
Enregistrer un commentaire