Primitve Boxing StackManipulation - byte-buddy

There seems to be a difference in the implementation of PrimitiveBoxingDelegate and PrimitiveUnboxingDelegate.
Basically I would like to box a primitive value on the stack, so it can be returned as a reference (ie. the method returns Object)
PrimitiveUnboxingDelegate.forPrimitive() provides me with a StackManipulation but unfortunately PrimitiveBoxingDelegate.forPrimitive() does not.
Is there an easy way to create a boxing StackManipulation?

You can, you just need to specify the type to which the value should be boxed to what is implicit for unboxing:
StackManipulation sm = PrimitiveBoxingDelegate
.forPrimitive(...)
.assignBoxedTo(..., Assigner.DEFAULT, Assigner.Typing.STATIC);
You can cast an int to for example a Object or a Number. You can however create illegal combinations as well what is sometimes necessary for Byte Buddy's own purposes.

Related

What is the point of CTypeDynamic?

I'm using reflection to serialize an object. Getting the values as objects is a real murder on performance due to late binding penalties. CType / DirectCast can get rid of most of it but I can't feed a type variable into it so currently I'm using a switch case block on the type variable to select the correct DirectCast.
It came to my attention that CTypeDynamic exists and takes type variables but the return type is Object so... it converts an object into an object, cool. That got me wondering, what is the purpose of this function?
The CTypeDynamic function looks for dynamic information and performs the cast/conversion appropriately. This is different from the CType operator which looks for static information at compile time or relies on the types being IConvertible.
This function examines the object at runtime including looking for Shared (aka static) custom operators. As always, if you know the type then use CType, but if you need dynamic casting then you need to use CTypeDynamic.
More information here: http://blogs.msmvps.com/bill/2010/01/24/ctypedynamic/

Check/display the declared type of an entity (variable, expression...)

I am investigating types in VB especially in VBA. Generally, given an entity there are two types: Effective value type, I guess, is defined as value types in this part of the specification; Declared Type is defined in this part of the specification.
To do tests, I need to use some functions to check types. There are TypeName and VarType. I think they are used to check effective value type of an entity, because TypeName can return DBNull, Decimal and Nothing; VarType can return vbNull, vbEmpty, vbError and vbDecimal. These types exist in the table of effective value types, but not in the table of declared type.
So now, my question is, does anyone know how to check/display the declared type of an entity (variable, expression...)?
Edit 1: Probably for a variable, its declared type is just the type that the declaration of the variable specifies. I would like to insist that, it seems that VBA has declared type for expressions. For instance, Operator Declared Type is mentioned in this link. I think that refers to the declared type of the result of an operation. That means such entities as -i, i+5, i>6... can have a declared type. I would like to know how to display their declared type.
If,
Dim i as integer
i = 6/3
then you do, TypeName(i>3)
it returns Boolean which is the expression's Type based on the Type of the resulting value it holds not operand's declare type. And it complies with the specification given in your link for msdn 2.2 Entities and Declared Types.
Or else are you looking for a syntax/function (e.g. DType, imaginative function) that could return DType(i>3) as integer which is operand's (i) Type? Or rather it's more useful when you have multiple variables within some expression, so you can find all their Types in one go?
e.g. some String that combined all sorts of different TYPE variables in one expressoin.
Just trying to understand when and how this can be useful to you and what could be the end result you are looking for.. Seems like this is more to lanague root definitions.
PS: I do not have reps points to comment. So I added as an answer.

Why does variance in .NET 4 only support reference types?

.NET 4 supports co- and contravariance. However, only reference types are supported, not value types. Why is that?
Basically the CLR needs to know that it can treat a value of the "source" type as a value of the "target" type without performing any extra conversions - to put it simply, the bit pattern for the source value has to be valid as the target value. The representations have to be the same. Otherwise the CLR would need to have extra information to perform the right conversions at the right time.
Eric Lippert has blogged about representation and identity - see that post for more information (as ever :).
Jon is right; to just expand on that a bit. Suppose you have
Func<int> f1 = ()=>2;
Func<object> f2 = f1;
object o1 = f1();
object o2 = f2();
Suppose that were legal. The compiler generates a boxing instruction; the third line is effectively:
object o1 = BoxIntegerToObject(f1());
Clearly the result stored in o2 should be a boxed int. Where is the boxing instruction? It cannot be after the call to f2, because that thing is guaranteed to return an object already. It cannot be in the call to f2, because the call to f2 is actually a call to f1, and f1 guarantees that it returns an unboxed int.
So the boxing instruction cannot happen after the call returns, and it cannot happen before the call returns, and therefore it cannot happen at all, and therefore this must be illegal. There is no reference conversion from Func<int> to Func<object>.
Both forms of variance are defined in terms of inheritance: value types aren't inherited.

CLI/C++ Converting "this" pointer to an integer

I am trying to trace managed object creation/disposing in a CLI/C++ prog:
::System::Diagnostics::Trace::WriteLine(String::Format(
"Created {0} #{1:X8}",
this->GetType()->Name,
((UInt64)this).ToString()));
Which fails with
error C2440: 'type cast' : cannot convert from 'MyType ^const ' to 'unsigned __int64'
Is there a way to keep track of the unique object IDs this way?
Thanks!
First of all, why this doesn't work. Managed handle types ^ aren't pointers. They aren't just addresses. An instance of a managed type can and will be moved around in memory by GC, so addresses aren't stable; hence why it wouldn't let you do such a cast (as GC can execute at any moment, and you do not know when, any attempt to use such an address as a raw value is inherently a race condition).
Another thing that is often recommended, but doesn't actually work, is Object.GetHashCode(). For one thing, it returns an int, obviously not enough to be unique on x64. Furthermore, the documentation doesn't guarantee that values are unique, and they actually aren't in 2.0+.
The only working solution is to create a an instance of System.Runtime.InteropServices.GCHandle for your object, and then cast it to IntPtr - that is guaranteed to be both unique, and stable.
Check out the GCHandle type: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.gchandle.aspx. Looks like it would do what you want, though it looks it would be a bit of a pain to use for your purposes...
Even if you could cast this to some integral value for display, it probably wouldn't be a useful unique identifier. This is because unlike C++, in C++/CLI the location of a (managed) object (and by extension the value of this) can potentially change during that object's lifetime. The (logically) same object could print two different strings at different points in the program.
MyType ^const is a reference type. Hence it's in the managed memory space, and you can't get direct memory pointers to these types, as they can change at any time.
Is there a way to keep track of the unique object IDs this way? Thanks!
You could use MyType.GetHashCode();

Does static typing mean that you have to cast a variable if you want to change its type?

Are there any other ways of changing a variable's type in a statically typed language like Java and C++, except 'casting'?
I'm trying to figure out what the main difference is in practical terms between dynamic and static typing and keep finding very academic definitions. I'm wondering what it means in terms of what my code looks like.
Make sure you don't get static vs. dynamic typing confused with strong vs. weak typing.
Static typing: Each variable, method parameter, return type etc. has a type known at compile time, either declared or inferred.
Dynamic typing: types are ignored/don't exist at compile time
Strong typing: each object at runtime has a specific type, and you can only perform those operations on it that are defined for that type.
Weak typing: runtime objects either don't have an explicit type, or the system attempts to automatically convert types wherever necessary.
These two opposites can be combined freely:
Java is statically and strongly typed
C is statically and weakly typed (pointer arithmetics!)
Ruby is dynamically and strongly typed
JavaScript is dynamically and weakly typed
Genrally, static typing means that a lot of errors are caught by the compiler which are runtime errors in a dynamically typed language - but it also means that you spend a lot of time worrying about types, in many cases unnecessarily (see interfaces vs. duck typing).
Strong typing means that any conversion between types must be explicit, either through a cast or through the use of conversion methods (e.g. parsing a string into an integer). This means more typing work, but has the advantage of keeping you in control of things, whereas weak typing often results in confusion when the system does some obscure implicit conversion that leaves you with a completely wrong variable value that causes havoc ten method calls down the line.
In C++/Java you can't change the type of a variable.
Static typing: A variable has one type assigned at compile type and that does not change.
Dynamic typing: A variable's type can change while runtime, e.g. in JavaScript:
js> x="5" <-- String
5
js> x=x*5 <-- Int
25
The main difference is that in dynamically typed languages you don't know until you go to use a method at runtime whether that method exists. In statically typed languages the check is made at compile time and the compilation fails if the method doesn't exist.
I'm wondering what it means in terms of what my code looks like.
The type system does not necessarily have any impact on what code looks like, e.g. languages with static typing, type inference and implicit conversion (like Scala for instance) look a lot like dynamically typed languages. See also: What To Know Before Debating Type Systems.
You don't need explicit casting. In many cases implicit casting works.
For example:
int i = 42;
float f = i; // f ~= 42.0
int b = f; // i == 42
class Base {
};
class Subclass : public Base {
};
Subclass *subclass = new Subclass();
Base *base = subclass; // Legal
Subclass *s = dynamic_cast<Subclass *>(base); // == subclass. Performs type checking. If base isn't a Subclass, NULL is returned instead. (This is type-safe explicit casting.)
You cannot, however, change the type of a variable. You can use unions in C++, though, to achieve some sort of dynamic typing.
Lets look at Java for he staitically typed language and JavaScript for the dynamc. In Java, for objects, the variable is a reference to an object. The object has a runtime type and the reference has a type. The type of the reference must be the type of the runtime object or one of its ancestors. This is how polymorphism works. You have to cast to go up the hierarchy of the reference type, but not down. The compiler ensures that these conditions are met. In a language like JavaScript, your variable is just that, a variable. You can have it point to whatever object you want, and you don't know the type of it until you check.
For conversions, though, there are lots of methods like toInteger and toFloat in Java to do a conversion and generate an object of a new type with the same relative value. In JavaScript there are also conversion methods, but they generate new objects too.
Your code should actally not look very much different, regardless if you are using a staticly typed language or not. Just because you can change the data type of a variable in a dynamically typed language, doesn't mean that it is a good idea to do so.
In VBScript, for example, hungarian notation is often used to specify the preferred data type of a variable. That way you can easily spot if the code is mixing types. (This was not the original use of hungarian notation, but it's pretty useful.)
By keeping to the same data type, you avoid situations where it's hard to tell what the code actually does, and situations where the code simply doesn't work properly. For example:
Dim id
id = Request.QueryString("id") ' this variable is now a string
If id = "42" Then
id = 142 ' sometimes turned into a number
End If
If id > 100 Then ' will not work properly for strings
Using hungarian notation you can spot code that is mixing types, like:
lngId = Request.QueryString("id") ' putting a string in a numeric variable
strId = 42 ' putting a number in a string variable