PInvoke Implementation on Fields - c#

So today I was browsing around ILSpy to get a better understanding of how .NET performs DllImports on external methods, when I came across something odd:
When searching for references to the enum value PInvokeImpl, which is defined in the System.Reflection.MethodAttributes enumeration, I noticed a matching definition in System.Reflection.FieldAttributes.
Well sure enough, this appears to be more than just a behind-the-scenes, re-use of enumeration values: System.Reflection.FieldInfo has an publicly defined property called IsPinvokeImpl, which specifically checks if this implementation flag is set.
Interestingly enough, the MethodInfo class doesn't even have this property - it must be determined from the MethodImplementationFlags property instead.
Question:
Is it actually possible for a field to be PInvoke implemented, or is this just a stub implementation in the .NET framework for balance between field decorations and method decorations?
If it is possible, can it be done in C#, or is this a feature that requires C++/CLI?

When you look at the MSDN description for FieldAttributes then you'll see it documented as "Reserved for future use". That future has not arrived yet so its intention is not nailed down.
Types like FieldAttributes are not arbitrary, they follow the CLI specification. Ecma-335 nails down what the metadata in a .NET assembly needs to look like and how it should be interpreted. This document does reveal an interesting quirk.
Chapter II.16.1 describes the field attributes, you'll see a close match between the metadata tokens and the FieldAttributes enum. Note however that pinvokeimpl is missing in that chapter.
Chapter II.23.1.5 gives the specific values of the attributes, it has PInvokeImpl with the value 0x2000. Description is "Implementation is forwarded through PInvoke". Compare to II.23.1.10, describes method attributes. It has many values in common with field attributes.
This looks a lot like a copy/paste bug :)
Digging a bit deeper through the .NET Framework source code, the CLR and jitter only ever considers pinvokeimpl on methods. The C# compiler however appears to be based on the CLI spec and actually sets the attribute. Appears in emit.cpp, RegMeta::_DefinePinvokeMap() function, it will set the attribute if this function is called for a field instead of a method. That never actually happens.

From FieldAttributes:
PinvokeImpl Reserved for future use.
So I would say:
Q: Is it actually possible for a field to be PInvoke implemented
A: No

Related

Retrieve custom attributes of Type in .NET Standard

I'd like to use C#'s reflection and custom attributes to simplify registering a series of types with a central management class (i.e. it provides static methods taking a string key and invoking/retrieving the proper method/parameter for the associated type). Looking at other questions here and a couple places elsewhere, it seems like the best way of doing so is to simply iterate through all public types of the assembly -- since it's intended to be a library -- and check if each type has the proper attribute before adding the relevant values to the underlying Dictionaries. The reflection and iteration will definitely be slow, but I can live with it since it should only occur once.
Unfortunately, I can't figure out how to get an attribute from a type. For methods and assemblies, I can use CustomAttributeExtensions.GetCustomAttribute<MyAttribute>(base) from System.Reflection.Extensions, but that doesn't provide an overload for Type; the same for Assembly.GetCustomAttribute(Assembly, Type) and the .IsDefined(...) methods used in this question. Other suggestions use methods on the Type itself that, from the documentation, seem to be loaded from mscorelib.dll, but it didn't seem to be showing up in Intellisense even after adding the reference and I'm not sure how that .dll interacts with .NET Standard, anyway (as in, does it reduce the ability to run on arbitrary platforms at all?)
Am I missing something obvious, or is it really this hard to get an Attribute back off of a Type?
Try typeof(YourType).GetTypeInfo().GetCustomAttributes();

What "Attributes" really are?

I've already read a lot about attributes and I know rather much about them.
But one thing that I can't understand is : "What they really are?".
I mean if this isn't inheritance or interface implementation or other OOP understandable concepts so what concept is this?
what happens behind the scene when you use and attribute for a class or a class member?
I have read other related posts in this site. But they don't give much information about what really happens. They are more about usage of attributes. And an incomprehensibility explanation of what they really are.In the other post this is what declares them : "Metadata. Data about your objects/methods/properties." which doesn't clarify concepts
They are simply metadata stored in the underlying definition (not instance) of the type. For example, if I do:
[Description("some text")]
public string Name {get;set;}
then the fact that DescriptionAttribute with a description constructor-parameter of "some text" is stored in the IL against the property Name. This has no impact on the cost of each instance, and it does nothing by itself. The only time this data is used is if code explicitly asks the runtime something like:
"what additional attribute metadata do you have against Name ?"
"does Name have a DescriptionAttribute ?"
"please construct me the DescriptionAttribute stored against Name, if one"
and then does something with the result.
CAVEAT: there are some attributes that are processed differently by the compiler and/or CLI, and are implemented differently. [Serializable], for example, becomes an IL type flag - not an IL attribute - but the runtime shims it so that the APIs report it as though it were the other.
Attributes are a very simple concept, but they are complicated by the fact that so many parts of the framework use them in ways that seem like magic.
Attributes are nothing more than Metadata. That is, they are essentially comments that the framework can read at runtime that describe things about the type. There are all kinds of attributes that are for various purposes, and there is various code written that looks for these attributes.
Attributes by themselves don't do anything. They need some other code to read them, and then do something based on what they find.
Attribute classes can be instantiated, and then code in them can be executed, but again, only if some other code requests it. Much of this code is often hidden by frameworks. For instance, in MVC there are attributes used for declaring methods to be Post or Get methods... or that a method must be authenticated before it can be called... These attributes are only useful because the MVC framework has code to check for them, and take action based on them.
In short, an attribute does nothing by itself. It only functions in conjunction with other code (usually in the framework) that makes use of it. As such, attributes can be almost anything that anyone can dream up.

protobuf-net missing has_ function for optional fields?.

We use protocol buffers for communication between native C++ apps, but also between native C++ app and .NET application (all is VS2012) via protobuf-net r666.
We rely in C++ heavily on the has_ functions that are available for an optional element.
E.g. if we have a message with a field optional bool, it can be that it is not set, it is set to true, or it is set to false.
In C++ this can be checked with the function has_field and if set then the content can be fetched with get_field function. If not set, and get_field is called, then the get returns the default, which if not explicitly set is false (for a boolean).
This works perfectly in C++, but, in protobuf-net however, we cannot seem to find the equivalent of the has_ function, and, when the message is received, the field is added to the message and it's content is set to the default, being false. It's not a disaster that the field is there with the default, but the problem is that there is no has_ function to check whether it was set in the message.
Please advise whether this is a bug or whether we missed something in protobuf-net and that this actually is possible
Thx in advance.
Wim
(I know we already covered this in the issue tracker - this is purely for visibility etc)
This relates to generating classes from .proto files, which in the case of protobuf-net is via the protogen tool. By default, it does not create the equivalent of has_* methods, but this can be enabled with the -p:detectMissing switch - which causes it to create *Specified accessors. The naming here is a .NET idiom, with *Specified recognised by some other .NET serializers and internal code. It also generates a private ShouldSerialize* method, which again helps some internal .NET code.
In this specific case, there was a secondary issue with a member called value causing confusion; the csharp.xslt file has now been updated to account for this.
Update: in the fully managed rewrite, the ShouldSerialize*() method is generated by default when using proto2 syntax (the default). No additional parameter is required. The *Specified member is not added (it serves no additional purpose over ShouldSerialize*().
Note that when using proto3, the changes to serialization rules mean that this concept no longer has meaning. A value is serialized if and only if it is not the default, which is always null/false/zero/empty. There is no concept of "the default value but specified". Because of this, the ShouldSerialize*() methods are generally no longer useful, and are not generated. I'm open to making them optionally generated for proto3, with them basically meaning "non-default", if that helps some genuine coding scenario.

When are ParameterInfo.IsLcid or ParameterInfo.IsRetval true?

I find this question in Stack Overflow when googleing, but it has been deleted. So I list this question again.
As I can't find the LcidAttribute or RetvalAttribute in BCL, I guess C# hasn't provided the support for locale identifier parameter and return value parameter.
Is that it?
Thanks all.
They are associated with the ParameterAttributes enumeration. Which is used in metadata for the parameter of a method, only a compiler can emit the [modopt].
I do not know of a compiler that actually does this. I have a decent guess at the background though, these attributes are also used in IDL. Which is an interface description language that is used in COM and RPC. Having this option ensures that .NET metadata can also describe the kind of declarations that are written in IDL and can appear in type libraries.
The [lcid] attribute is described here. It doesn't actually describe usage and I've never used it myself. No real idea why you'd use it.
The [retval] attribute is described here. Very important in COM automation method declarations, it marks the parameter that returns the method value. And used by a tool like Tlbimp.exe, it rewrites the method to make that parameter the return value type.

What guidelines are appropriate for determining when to implement a class member as a property versus a method?

The .NET coding standards PDF from SubMain that have started showing up in the "Sponsored By" area seems to indicate that properties are only appropriate for logical data members (see pages 34-35 of the document). Methods are deemed appropriate in the following cases:
The operation is a conversion, such as Object.ToString().
The operation is expensive enough that you want to communicate to the user that they should consider caching the result.
Obtaining a property value using the get accessor would have an observable side effect.
Calling the member twice in succession produces different results.
The order of execution is important.
The member is static but returns a value that can be changed.
The member returns an array.
Do most developers agree on the properties vs. methods argument above? If so, why? If not, why not?
They seem sound, and basically in line with MSDN member design guidelines:
http://msdn.microsoft.com/en-us/library/ms229059.aspx
One point that people sometimes seem to forget (*) is that callers should be able to set properties in any order. Particularly important for classes that support designers, as you can't be sure of the order generated code will set properties.
(*) I remember early versions of the Ajax Control Toolkit on Codeplex had numerous bugs due to developers forgetting this one.
As for "Calling the member twice in succession produces different results", every rule has an exception, as the property DateTime.Now illustrates.
Those are interesting guidelines, and I agree with them. It's interesting in that they are setting the rules based on "everything is a property except the following". That said, they are good guidelines for avoiding problems by defining something as a property that can cause issues later.
At the end of the day a property is just a structured method, so the rule of thumb I use is based on Object Orientation -- if the member represents data owned by the entity, it should be defined as a property; if it represents behavior of the entity it should be implemented as a method.
Fully agreed.
According to the coding guidelines properties are "nouns" and methods are "verbs". Keep in mind that a user may call the property very often while thinking it would be a "cheap" operation.
On the other side it's usually expected that a method may "take more time", so a user considers about caching method results.
What's so interesting about those guidelines is that they are clearly an argument for having extension properties as well as extension methods. Shame.
I never personally came to the conclusion or had the gut feeling that properties are fast, but the guidelines say they should be, so I just accept it.
I always struggle with what to name my slow "get" methods while avoiding FxCop warnings. GetPeopleList() sounds good to me, but then FxCop tells me it might be better as a property.

Categories