Jan 282014
 
Share
Introduction

I’ve got a native console application which would like to call into a piece of managed code written in C#. This is the how the C# function “Sum” looks like…

image

My solution explorer looks as follows…

image

CSharpModule is a CSharp library while TestManagedCall is a native/unmanaged project. My requirement is as follows: call Class1.Sum from TestManagedCall project.

 
Adding Reference

To do this we’ll need to first add a reference of CSharpModule to TestManagedCall project. Go to project properties of TestManagedCall project and add a reference to CSharpModule project, see below screenshot…

image

So the reference of CSharpModule is now added to TestManagedCall project.

 
Project changes

Next step is to add a new C++ file to TestManagedCall project. I’ll call the file: CSharpModuleWrapper.cpp, this class will act as a wrapper to our managed library: CSharpModule. This is how my solution will explorer look now…

image

Right click on CSharpModuleWrapper.cpp in the solution explorer, select properties, and enable CLR for just this one file

image

 
Fixing incompatibilities

Click “Ok”. Now do a full rebuild. You should see following errors pop up, fix them one by one since adding CLR support results in these incompatibilities… (you’ll see these errors popup one by one, so fixing one will lead to another. Keep fixing them and you’ll see the next error).

  1. cl : Command line error D8016: ‘/ZI’ and ‘/clr’ command-line options are incompatible. Open the file’s(CSharpModuleWrapper.cpp) properties and go to “All Options” under C/C++ node. This is a cool feature to quickly search for an option the properties dialog. Search for /ZI as given in the above error message. CLR compilation doesn’t support /ZI change it to /Zi.
    image
  2. cl : Command line error D8016: ‘/clr’ and ‘/Gm’ command-line options are incompatible. Again open file’s properties and goto “All Options” under C/C++ node. Search for /Gm as given in the above message… (disable minimal rebuild). Change to /Gm-
    image
  3. cl : Command line error D8016: ‘/clr’ and ‘/EHs’ command-line options are incompatible. In file’s properties search for /EHs. Switch to /EHa.
    image
  4. cl : Command line error D8016: ‘/clr’ and ‘/RTC1′ command-line options are incompatible. Change to Default as shown below…
    image
  5. Disable pre-compiled headers as shown below, search for /Yu under “C/C++->All options”…
    image

With these changes your code will compile. I get following output…

image

 
Code Changes

Now add code to use the CSharpModule’s namespace and add a function to CSharpModuleWrapper class. Eventually this is how my code will look like with all the modifications…

image

The CSharpModuleWrapper.h has only one change, I added a declaration for Call_Sum().

Don’t forget to call Call_Sum(). This is how the calling code looks like…

image

 
Output…

image

This is a reliable way to make calls into managed world from native world. Of course there are #pragma’s (managed/unmanaged) that you can use but I’m not so confident about using them. This is clean!

 
Conclusion

The sample I’ve shown is a ‘very’ simple one, I’m sure you’ll have a variety of requirements, let me know if I can help.

Share
Jan 252014
 
Share

Taken from MSDN: http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes_fields(v=vs.120).aspx 

Public field Static member
Add
Adds two values and pushes the result onto the evaluation stack.

Public field Static member
Add_Ovf
Adds two integers, performs an overflow check, and pushes the result onto the evaluation stack.

Public field Static member
Add_Ovf_Un
Adds two unsigned integer values, performs an overflow check, and pushes the result onto the evaluation stack.

Public field Static member
And
Computes the bitwise AND of two values and pushes the result onto the evaluation stack.

Public field Static member
Arglist
Returns an unmanaged pointer to the argument list of the current method.

Public field Static member
Beq
Transfers control to a target instruction if two values are equal.

Public field Static member
Beq_S
Transfers control to a target instruction (short form) if two values are equal.

Public field Static member
Bge
Transfers control to a target instruction if the first value is greater than or equal to the second value.

Public field Static member
Bge_S
Transfers control to a target instruction (short form) if the first value is greater than or equal to the second value.

Public field Static member
Bge_Un
Transfers control to a target instruction if the first value is greater than the second value, when comparing unsigned integer values or unordered float values.

Public field Static member
Bge_Un_S
Transfers control to a target instruction (short form) if the first value is greater than the second value, when comparing unsigned integer values or unordered float values.

Public field Static member
Bgt
Transfers control to a target instruction if the first value is greater than the second value.

Public field Static member
Bgt_S
Transfers control to a target instruction (short form) if the first value is greater than the second value.

Public field Static member
Bgt_Un
Transfers control to a target instruction if the first value is greater than the second value, when comparing unsigned integer values or unordered float values.

Public field Static member
Bgt_Un_S
Transfers control to a target instruction (short form) if the first value is greater than the second value, when comparing unsigned integer values or unordered float values.

Public field Static member
Ble
Transfers control to a target instruction if the first value is less than or equal to the second value.

Public field Static member
Ble_S
Transfers control to a target instruction (short form) if the first value is less than or equal to the second value.

Public field Static member
Ble_Un
Transfers control to a target instruction if the first value is less than or equal to the second value, when comparing unsigned integer values or unordered float values.

Public field Static member
Ble_Un_S
Transfers control to a target instruction (short form) if the first value is less than or equal to the second value, when comparing unsigned integer values or unordered float values.

Public field Static member
Blt
Transfers control to a target instruction if the first value is less than the second value.

Public field Static member
Blt_S
Transfers control to a target instruction (short form) if the first value is less than the second value.

Public field Static member
Blt_Un
Transfers control to a target instruction if the first value is less than the second value, when comparing unsigned integer values or unordered float values.

Public field Static member
Blt_Un_S
Transfers control to a target instruction (short form) if the first value is less than the second value, when comparing unsigned integer values or unordered float values.

Public field Static member
Bne_Un
Transfers control to a target instruction when two unsigned integer values or unordered float values are not equal.

Public field Static member
Bne_Un_S
Transfers control to a target instruction (short form) when two unsigned integer values or unordered float values are not equal.

Public field Static member
Box
Converts a value type to an object reference (type O).

Public field Static member
Br
Unconditionally transfers control to a target instruction.

Public field Static member
Br_S
Unconditionally transfers control to a target instruction (short form).

Public field Static member
Break
Signals the Common Language Infrastructure (CLI) to inform the debugger that a break point has been tripped.

Public field Static member
Brfalse
Transfers control to a target instruction if value is false, a null reference (Nothing in Visual Basic), or zero.

Public field Static member
Brfalse_S
Transfers control to a target instruction if value is false, a null reference, or zero.

Public field Static member
Brtrue
Transfers control to a target instruction if value is true, not null, or non-zero.

Public field Static member
Brtrue_S
Transfers control to a target instruction (short form) if value is true, not null, or non-zero.

Public field Static member
Call
Calls the method indicated by the passed method descriptor.

Public field Static member
Calli
Calls the method indicated on the evaluation stack (as a pointer to an entry point) with arguments described by a calling convention.

Public field Static member
Callvirt
Calls a late-bound method on an object, pushing the return value onto the evaluation stack.

Public field Static member
Castclass
Attempts to cast an object passed by reference to the specified class.

Public field Static member
Ceq
Compares two values. If they are equal, the integer value 1 (int32) is pushed onto the evaluation stack; otherwise 0 (int32) is pushed onto the evaluation stack.

Public field Static member
Cgt
Compares two values. If the first value is greater than the second, the integer value 1 (int32) is pushed onto the evaluation stack; otherwise 0 (int32) is pushed onto the evaluation stack.

Public field Static member
Cgt_Un
Compares two unsigned or unordered values. If the first value is greater than the second, the integer value 1 (int32) is pushed onto the evaluation stack; otherwise 0 (int32) is pushed onto the evaluation stack.

Public field Static member
Ckfinite
Throws ArithmeticException if value is not a finite number.

Public field Static member
Clt
Compares two values. If the first value is less than the second, the integer value 1 (int32) is pushed onto the evaluation stack; otherwise 0 (int32) is pushed onto the evaluation stack.

Public field Static member
Clt_Un
Compares the unsigned or unordered values value1 and value2. If value1 is less than value2, then the integer value 1 (int32) is pushed onto the evaluation stack; otherwise 0 (int32) is pushed onto the evaluation stack.

Public field Static member
Constrained
Constrains the type on which a virtual method call is made.

Public field Static member
Conv_I
Converts the value on top of the evaluation stack to native int.

Public field Static member
Conv_I1
Converts the value on top of the evaluation stack to int8, then extends (pads) it to int32.

Public field Static member
Conv_I2
Converts the value on top of the evaluation stack to int16, then extends (pads) it to int32.

Public field Static member
Conv_I4
Converts the value on top of the evaluation stack to int32.

Public field Static member
Conv_I8
Converts the value on top of the evaluation stack to int64.

Public field Static member
Conv_Ovf_I
Converts the signed value on top of the evaluation stack to signed native int, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_I_Un
Converts the unsigned value on top of the evaluation stack to signed native int, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_I1
Converts the signed value on top of the evaluation stack to signed int8 and extends it to int32, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_I1_Un
Converts the unsigned value on top of the evaluation stack to signed int8 and extends it to int32, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_I2
Converts the signed value on top of the evaluation stack to signed int16 and extending it to int32, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_I2_Un
Converts the unsigned value on top of the evaluation stack to signed int16 and extends it to int32, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_I4
Converts the signed value on top of the evaluation stack to signed int32, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_I4_Un
Converts the unsigned value on top of the evaluation stack to signed int32, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_I8
Converts the signed value on top of the evaluation stack to signed int64, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_I8_Un
Converts the unsigned value on top of the evaluation stack to signed int64, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_U
Converts the signed value on top of the evaluation stack to unsigned native int, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_U_Un
Converts the unsigned value on top of the evaluation stack to unsigned native int, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_U1
Converts the signed value on top of the evaluation stack to unsigned int8 and extends it to int32, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_U1_Un
Converts the unsigned value on top of the evaluation stack to unsigned int8 and extends it to int32, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_U2
Converts the signed value on top of the evaluation stack to unsigned int16 and extends it to int32, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_U2_Un
Converts the unsigned value on top of the evaluation stack to unsigned int16 and extends it to int32, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_U4
Converts the signed value on top of the evaluation stack to unsigned int32, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_U4_Un
Converts the unsigned value on top of the evaluation stack to unsigned int32, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_U8
Converts the signed value on top of the evaluation stack to unsigned int64, throwing OverflowException on overflow.

Public field Static member
Conv_Ovf_U8_Un
Converts the unsigned value on top of the evaluation stack to unsigned int64, throwing OverflowException on overflow.

Public field Static member
Conv_R_Un
Converts the unsigned integer value on top of the evaluation stack to float32.

Public field Static member
Conv_R4
Converts the value on top of the evaluation stack to float32.

Public field Static member
Conv_R8
Converts the value on top of the evaluation stack to float64.

Public field Static member
Conv_U
Converts the value on top of the evaluation stack to unsigned native int, and extends it to native int.

Public field Static member
Conv_U1
Converts the value on top of the evaluation stack to unsigned int8, and extends it to int32.

Public field Static member
Conv_U2
Converts the value on top of the evaluation stack to unsigned int16, and extends it to int32.

Public field Static member
Conv_U4
Converts the value on top of the evaluation stack to unsigned int32, and extends it to int32.

Public field Static member
Conv_U8
Converts the value on top of the evaluation stack to unsigned int64, and extends it to int64.

Public field Static member
Cpblk
Copies a specified number bytes from a source address to a destination address.

Public field Static member
Cpobj
Copies the value type located at the address of an object (type &, * or native int) to the address of the destination object (type &, * or native int).

Public field Static member
Div
Divides two values and pushes the result as a floating-point (type F) or quotient (type int32) onto the evaluation stack.

Public field Static member
Div_Un
Divides two unsigned integer values and pushes the result (int32) onto the evaluation stack.

Public field Static member
Dup
Copies the current topmost value on the evaluation stack, and then pushes the copy onto the evaluation stack.

Public field Static member
Endfilter
Transfers control from the filter clause of an exception back to the Common Language Infrastructure (CLI) exception handler.

Public field Static member
Endfinally
Transfers control from the fault or finally clause of an exception block back to the Common Language Infrastructure (CLI) exception handler.

Public field Static member
Initblk
Initializes a specified block of memory at a specific address to a given size and initial value.

Public field Static member
Initobj
Initializes each field of the value type at a specified address to a null reference or a 0 of the appropriate primitive type.

Public field Static member
Isinst
Tests whether an object reference (type O) is an instance of a particular class.

Public field Static member
Jmp
Exits current method and jumps to specified method.

Public field Static member
Ldarg
Loads an argument (referenced by a specified index value) onto the stack.

Public field Static member
Ldarg_0
Loads the argument at index 0 onto the evaluation stack.

Public field Static member
Ldarg_1
Loads the argument at index 1 onto the evaluation stack.

Public field Static member
Ldarg_2
Loads the argument at index 2 onto the evaluation stack.

Public field Static member
Ldarg_3
Loads the argument at index 3 onto the evaluation stack.

Public field Static member
Ldarg_S
Loads the argument (referenced by a specified short form index) onto the evaluation stack.

Public field Static member
Ldarga
Load an argument address onto the evaluation stack.

Public field Static member
Ldarga_S
Load an argument address, in short form, onto the evaluation stack.

Public field Static member
Ldc_I4
Pushes a supplied value of type int32 onto the evaluation stack as an int32.

Public field Static member
Ldc_I4_0
Pushes the integer value of 0 onto the evaluation stack as an int32.

Public field Static member
Ldc_I4_1
Pushes the integer value of 1 onto the evaluation stack as an int32.

Public field Static member
Ldc_I4_2
Pushes the integer value of 2 onto the evaluation stack as an int32.

Public field Static member
Ldc_I4_3
Pushes the integer value of 3 onto the evaluation stack as an int32.

Public field Static member
Ldc_I4_4
Pushes the integer value of 4 onto the evaluation stack as an int32.

Public field Static member
Ldc_I4_5
Pushes the integer value of 5 onto the evaluation stack as an int32.

Public field Static member
Ldc_I4_6
Pushes the integer value of 6 onto the evaluation stack as an int32.

Public field Static member
Ldc_I4_7
Pushes the integer value of 7 onto the evaluation stack as an int32.

Public field Static member
Ldc_I4_8
Pushes the integer value of 8 onto the evaluation stack as an int32.

Public field Static member
Ldc_I4_M1
Pushes the integer value of -1 onto the evaluation stack as an int32.

Public field Static member
Ldc_I4_S
Pushes the supplied int8 value onto the evaluation stack as an int32, short form.

Public field Static member
Ldc_I8
Pushes a supplied value of type int64 onto the evaluation stack as an int64.

Public field Static member
Ldc_R4
Pushes a supplied value of type float32 onto the evaluation stack as type F (float).

Public field Static member
Ldc_R8
Pushes a supplied value of type float64 onto the evaluation stack as type F (float).

Public field Static member
Ldelem
Loads the element at a specified array index onto the top of the evaluation stack as the type specified in the instruction.

Public field Static member
Ldelem_I
Loads the element with type native int at a specified array index onto the top of the evaluation stack as a native int.

Public field Static member
Ldelem_I1
Loads the element with type int8 at a specified array index onto the top of the evaluation stack as an int32.

Public field Static member
Ldelem_I2
Loads the element with type int16 at a specified array index onto the top of the evaluation stack as an int32.

Public field Static member
Ldelem_I4
Loads the element with type int32 at a specified array index onto the top of the evaluation stack as an int32.

Public field Static member
Ldelem_I8
Loads the element with type int64 at a specified array index onto the top of the evaluation stack as an int64.

Public field Static member
Ldelem_R4
Loads the element with type float32 at a specified array index onto the top of the evaluation stack as type F (float).

Public field Static member
Ldelem_R8
Loads the element with type float64 at a specified array index onto the top of the evaluation stack as type F (float).

Public field Static member
Ldelem_Ref
Loads the element containing an object reference at a specified array index onto the top of the evaluation stack as type O (object reference).

Public field Static member
Ldelem_U1
Loads the element with type unsigned int8 at a specified array index onto the top of the evaluation stack as an int32.

Public field Static member
Ldelem_U2
Loads the element with type unsigned int16 at a specified array index onto the top of the evaluation stack as an int32.

Public field Static member
Ldelem_U4
Loads the element with type unsigned int32 at a specified array index onto the top of the evaluation stack as an int32.

Public field Static member
Ldelema
Loads the address of the array element at a specified array index onto the top of the evaluation stack as type & (managed pointer).

Public field Static member
Ldfld
Finds the value of a field in the object whose reference is currently on the evaluation stack.

Public field Static member
Ldflda
Finds the address of a field in the object whose reference is currently on the evaluation stack.

Public field Static member
Ldftn
Pushes an unmanaged pointer (type native int) to the native code implementing a specific method onto the evaluation stack.

Public field Static member
Ldind_I
Loads a value of type native int as a native int onto the evaluation stack indirectly.

Public field Static member
Ldind_I1
Loads a value of type int8 as an int32 onto the evaluation stack indirectly.

Public field Static member
Ldind_I2
Loads a value of type int16 as an int32 onto the evaluation stack indirectly.

Public field Static member
Ldind_I4
Loads a value of type int32 as an int32 onto the evaluation stack indirectly.

Public field Static member
Ldind_I8
Loads a value of type int64 as an int64 onto the evaluation stack indirectly.

Public field Static member
Ldind_R4
Loads a value of type float32 as a type F (float) onto the evaluation stack indirectly.

Public field Static member
Ldind_R8
Loads a value of type float64 as a type F (float) onto the evaluation stack indirectly.

Public field Static member
Ldind_Ref
Loads an object reference as a type O (object reference) onto the evaluation stack indirectly.

Public field Static member
Ldind_U1
Loads a value of type unsigned int8 as an int32 onto the evaluation stack indirectly.

Public field Static member
Ldind_U2
Loads a value of type unsigned int16 as an int32 onto the evaluation stack indirectly.

Public field Static member
Ldind_U4
Loads a value of type unsigned int32 as an int32 onto the evaluation stack indirectly.

Public field Static member
Ldlen
Pushes the number of elements of a zero-based, one-dimensional array onto the evaluation stack.

Public field Static member
Ldloc
Loads the local variable at a specific index onto the evaluation stack.

Public field Static member
Ldloc_0
Loads the local variable at index 0 onto the evaluation stack.

Public field Static member
Ldloc_1
Loads the local variable at index 1 onto the evaluation stack.

Public field Static member
Ldloc_2
Loads the local variable at index 2 onto the evaluation stack.

Public field Static member
Ldloc_3
Loads the local variable at index 3 onto the evaluation stack.

Public field Static member
Ldloc_S
Loads the local variable at a specific index onto the evaluation stack, short form.

Public field Static member
Ldloca
Loads the address of the local variable at a specific index onto the evaluation stack.

Public field Static member
Ldloca_S
Loads the address of the local variable at a specific index onto the evaluation stack, short form.

Public field Static member
Ldnull
Pushes a null reference (type O) onto the evaluation stack.

Public field Static member
Ldobj
Copies the value type object pointed to by an address to the top of the evaluation stack.

Public field Static member
Ldsfld
Pushes the value of a static field onto the evaluation stack.

Public field Static member
Ldsflda
Pushes the address of a static field onto the evaluation stack.

Public field Static member
Ldstr
Pushes a new object reference to a string literal stored in the metadata.

Public field Static member
Ldtoken
Converts a metadata token to its runtime representation, pushing it onto the evaluation stack.

Public field Static member
Ldvirtftn
Pushes an unmanaged pointer (type native int) to the native code implementing a particular virtual method associated with a specified object onto the evaluation stack.

Public field Static member
Leave
Exits a protected region of code, unconditionally transferring control to a specific target instruction.

Public field Static member
Leave_S
Exits a protected region of code, unconditionally transferring control to a target instruction (short form).

Public field Static member
Localloc
Allocates a certain number of bytes from the local dynamic memory pool and pushes the address (a transient pointer, type *) of the first allocated byte onto the evaluation stack.

Public field Static member
Mkrefany
Pushes a typed reference to an instance of a specific type onto the evaluation stack.

Public field Static member
Mul
Multiplies two values and pushes the result on the evaluation stack.

Public field Static member
Mul_Ovf
Multiplies two integer values, performs an overflow check, and pushes the result onto the evaluation stack.

Public field Static member
Mul_Ovf_Un
Multiplies two unsigned integer values, performs an overflow check, and pushes the result onto the evaluation stack.

Public field Static member
Neg
Negates a value and pushes the result onto the evaluation stack.

Public field Static member
Newarr
Pushes an object reference to a new zero-based, one-dimensional array whose elements are of a specific type onto the evaluation stack.

Public field Static member
Newobj
Creates a new object or a new instance of a value type, pushing an object reference (type O) onto the evaluation stack.

Public field Static member
Nop
Fills space if opcodes are patched. No meaningful operation is performed although a processing cycle can be consumed.

Public field Static member
Not
Computes the bitwise complement of the integer value on top of the stack and pushes the result onto the evaluation stack as the same type.

Public field Static member
Or
Compute the bitwise complement of the two integer values on top of the stack and pushes the result onto the evaluation stack.

Public field Static member
Pop
Removes the value currently on top of the evaluation stack.

Public field Static member
Prefix1
Infrastructure. This is a reserved instruction.

Public field Static member
Prefix2
Infrastructure. This is a reserved instruction.

Public field Static member
Prefix3
Infrastructure. This is a reserved instruction.

Public field Static member
Prefix4
Infrastructure. This is a reserved instruction.

Public field Static member
Prefix5
Infrastructure. This is a reserved instruction.

Public field Static member
Prefix6
Infrastructure. This is a reserved instruction.

Public field Static member
Prefix7
Infrastructure. This is a reserved instruction.

Public field Static member
Prefixref
Infrastructure. This is a reserved instruction.

Public field Static member
Readonly
Specifies that the subsequent array address operation performs no type check at run time, and that it returns a managed pointer whose mutability is restricted.

Public field Static member
Refanytype
Retrieves the type token embedded in a typed reference.

Public field Static member
Refanyval
Retrieves the address (type &) embedded in a typed reference.

Public field Static member
Rem
Divides two values and pushes the remainder onto the evaluation stack.

Public field Static member
Rem_Un
Divides two unsigned values and pushes the remainder onto the evaluation stack.

Public field Static member
Ret
Returns from the current method, pushing a return value (if present) from the callee’s evaluation stack onto the caller’s evaluation stack.

Public field Static member
Rethrow
Rethrows the current exception.

Public field Static member
Shl
Shifts an integer value to the left (in zeroes) by a specified number of bits, pushing the result onto the evaluation stack.

Public field Static member
Shr
Shifts an integer value (in sign) to the right by a specified number of bits, pushing the result onto the evaluation stack.

Public field Static member
Shr_Un
Shifts an unsigned integer value (in zeroes) to the right by a specified number of bits, pushing the result onto the evaluation stack.

Public field Static member
Sizeof
Pushes the size, in bytes, of a supplied value type onto the evaluation stack.

Public field Static member
Starg
Stores the value on top of the evaluation stack in the argument slot at a specified index.

Public field Static member
Starg_S
Stores the value on top of the evaluation stack in the argument slot at a specified index, short form.

Public field Static member
Stelem
Replaces the array element at a given index with the value on the evaluation stack, whose type is specified in the instruction.

Public field Static member
Stelem_I
Replaces the array element at a given index with the native int value on the evaluation stack.

Public field Static member
Stelem_I1
Replaces the array element at a given index with the int8 value on the evaluation stack.

Public field Static member
Stelem_I2
Replaces the array element at a given index with the int16 value on the evaluation stack.

Public field Static member
Stelem_I4
Replaces the array element at a given index with the int32 value on the evaluation stack.

Public field Static member
Stelem_I8
Replaces the array element at a given index with the int64 value on the evaluation stack.

Public field Static member
Stelem_R4
Replaces the array element at a given index with the float32 value on the evaluation stack.

Public field Static member
Stelem_R8
Replaces the array element at a given index with the float64 value on the evaluation stack.

Public field Static member
Stelem_Ref
Replaces the array element at a given index with the object ref value (type O) on the evaluation stack.

Public field Static member
Stfld
Replaces the value stored in the field of an object reference or pointer with a new value.

Public field Static member
Stind_I
Stores a value of type native int at a supplied address.

Public field Static member
Stind_I1
Stores a value of type int8 at a supplied address.

Public field Static member
Stind_I2
Stores a value of type int16 at a supplied address.

Public field Static member
Stind_I4
Stores a value of type int32 at a supplied address.

Public field Static member
Stind_I8
Stores a value of type int64 at a supplied address.

Public field Static member
Stind_R4
Stores a value of type float32 at a supplied address.

Public field Static member
Stind_R8
Stores a value of type float64 at a supplied address.

Public field Static member
Stind_Ref
Stores a object reference value at a supplied address.

Public field Static member
Stloc
Pops the current value from the top of the evaluation stack and stores it in a the local variable list at a specified index.

Public field Static member
Stloc_0
Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 0.

Public field Static member
Stloc_1
Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 1.

Public field Static member
Stloc_2
Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 2.

Public field Static member
Stloc_3
Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 3.

Public field Static member
Stloc_S
Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index (short form).

Public field Static member
Stobj
Copies a value of a specified type from the evaluation stack into a supplied memory address.

Public field Static member
Stsfld
Replaces the value of a static field with a value from the evaluation stack.

Public field Static member
Sub
Subtracts one value from another and pushes the result onto the evaluation stack.

Public field Static member
Sub_Ovf
Subtracts one integer value from another, performs an overflow check, and pushes the result onto the evaluation stack.

Public field Static member
Sub_Ovf_Un
Subtracts one unsigned integer value from another, performs an overflow check, and pushes the result onto the evaluation stack.

Public field Static member
Switch
Implements a jump table.

Public field Static member
Tailcall
Performs a postfixed method call instruction such that the current method’s stack frame is removed before the actual call instruction is executed.

Public field Static member
Throw
Throws the exception object currently on the evaluation stack.

Public field Static member
Unaligned
Indicates that an address currently atop the evaluation stack might not be aligned to the natural size of the immediately following ldind, stind, ldfld, stfld, ldobj, stobj, initblk, or cpblk instruction.

Public field Static member
Unbox
Converts the boxed representation of a value type to its unboxed form.

Public field Static member
Unbox_Any
Converts the boxed representation of a type specified in the instruction to its unboxed form.

Public field Static member
Volatile
Specifies that an address currently atop the evaluation stack might be volatile, and the results of reading that location cannot be cached or that multiple stores to that location cannot be suppressed.

Public field Static member
Xor
Computes the bitwise XOR of the top two values on the evaluation stack, pushing the result onto the evaluation stack.

Share
Jan 222014
 
Share

Visual Studio 2013 comes with a new feature called “Debug Managed Memory” this feature also allows to compare managed memory usage across two dumps.  Read on…

This is how you would open a .net 4.5 memory dump in Visual Studio…

imageimage

So for the purpose of this blog I’ve created memory dumps of a managed application that consumes high memory: memtest.exe. I’ve collected three memory dumps…

  1. MemTest.dmp
  2. MemTest (2).dmp
  3. MemTest (3).dmp

For demo purpose I’m opening MemTest (3).dmp ‘first’ as shown in the above screenshot. So once you open the dump in Visual studio this is how Visual Studio will look like…

image

Check out mouse cursor location in the above screenshot. Click on this option. You’ll following dialog pop up….

image

Following which you’ll see the following screen…

image

This report will show the most number of objects on heap. If you notice the largest objects in my case are ArrayLists and second one is MemTest.Form1, too many forms. The also shows you the roots to an object.

Further in the above screenshot, I’ve highlighted an item in red. That option allows us to compare multiple dumps. The resultant report will show you the diff view between the two dumps. For demo I’m comparing MemTest (3).dmp with MemTest.dmp. MemTest (3).dmp was collected after  memtest.dmp was collected so you should ideally see a positive diff between the two dumps as the memory is increasing. See screenshot…

image

You’ll see that, new columns has been added to this report, for e.g. “Cound Diff.”, ‘Size Diff (Bytes)” etc. The bottom table shows you the “Reference Count Diff.” as well.

Really cool feature! Comparing managed memory has been never easier. Please note this feature is only enabled for.net memory dumps that use .net 4.5.

Share
Jan 202014
 
Share

A video presentation on what’s new and cool in Visual Studio 2013 Solution Explorer…

I’ll follow up this presentation with some more presentation on what’s some of the cool things in Visual Studio 2013 just to speed up anyone who’s hopping onto the Visual Studio 2013 wagon.

Share
Dec 202013
 
Share

Note the VisualBasic PowerPack is not part of Visual Studio 2013 install, it comes as separate MSI. The download link for Visual Basic Powerpack for Visual Studio 2013 is hard to find online as well. I found the link from our internal support article.

Download VB Powerpack (direct link to bits): http://go.microsoft.com/fwlink/?LinkId=321343

Installing Visual Basic Powerpacks

Installing Visual Basic Powerpacks

Please close any open instances of Visual Studio 2013. Once the installation completes and if you still don’t see the Powerpack controls in the toolbox. Do the following.

  1. Open Visual Studio 2013
  2. Open the toolbox. Add a new tab, right click on the toolbox, select “Add Tab”. Name the tab to “Visual Basic PowerPack”
  3. Expand the new “Tab”. Right click in the empty space under the new tab and select “Choose Item”. You’ll see the following dialog popup…

    Adding reference to Visual Basic powerpack

    Adding reference to Visual Basic powerpack

  4. Please give it few minutes to load all items. Please select “.Net Framework Components” tab if its not already selected.
  5. In the filter text box control please type in “Power”. You should see something like this in the above dialog…

    Choose toolbox items

    Choose toolbox items

  6. Check the relevant ones and add them to your toolbox as shown below…

    Adding Filter for powerpack in the Choose toolbox items dialog

    Adding filter for powerpack in the Choose toolbox items dialog

  7. Once you click ok, you should see the following controls added to your toolbox…

    PowerPack controls listed in VS toolbox

    PowerPack controls listed in VS toolbox

  8. In my case I’ve added all powerpack controls to my toolbox.
  9. You might also have to add a reference to this new powerpack library if you still see compilation errors. Be aware that the assembly name has changed as well…

    Adding reference to new powerpack library

    Adding reference to new powerpack library

We’ve had couple of customer’s who report that Visual Basic powerpack is missing from Visual Studio 2013.
http://connect.microsoft.com/VisualStudio/feedback/details/801421/microsoft-visualbasic-powerpacks-vs-dll

Enjoy the powerpack.

Share
Dec 202013
 
Share

Had a customer whose application was crashing after migration from Visual Studio 2005 to Visual Studio 2008. He had the crash dumps as well. The crash call stack had some CRT string format functions like vsprintf. This gave to us a fair inkling that parameters passed in are wrong.

Customer had a format string, something like this: “My string format [%s]”.

At the point of crash the output buffer looked like this: “My string format[“. It became quite evident that the crash is happening when the %s in the format string was being replaced by the actual string. Quite evident that something’s wrong with the parameter passed in for replacing the %s format specifier.

Checking code saw something like this…

MyString mystr = “MS rocks”;
MyFormatters::Format(“My string format [%s]”, mystr);

You should never do this. %s is expecting a “raw string” and do not pass in anything else. This is wrong even if your class has a raw string as its first member, imagine if you have a virtual function in the class or if someone decides in the future this class should be derived further.

Always pass in a raw string pointer and nothing else to the string format functions for expanding the format specifier: %s. The string format family of functions doesn’t check the type passed in. Those functions work on varargs hence compiler doesn’t help as well.

In this case we fixed above code likewise:
MyFormatters::Format(“My string format [%s]”, mystr.c_str());

You might have an obvious question as to why it worked in Visual Studio 2005, the answer is pretty obvious as well. I’ll leave that for you to answer.

Share
Dec 092013
 
Share

Recently a colleague of mine asked where’s the length of CString string stored in memory. Hmm so lets dig around. Please note I’ve declared the following CString object in my code…

CString TestCString = _T("Nibu is testing CString");

If you dump CString type in the debugger we see following…

0:000> dt TestCString
Local var @ 0xb4fcd4 Type ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t> > >
   +0x000 m_pszData        : 0x00dfa2f8  "Nibu is testing CString"

From above dump of type CString we see that CString class defines just one variable: m_pszData. I don’t see a length variable here so where is the length stored for CString string?

Length of a CString string is stored at a negative offset from m_pszData. The data structure that resides at the negative offset is: ATL::CStringData

0:000> dt mfc100ud!ATL::CStringData
   +0x000 pStringMgr       : Ptr32 ATL::IAtlStringMgr
   +0x004 nDataLength      : Int4B
   +0x008 nAllocLength     : Int4B
   +0x00c nRefs            : Int4B

CStringData is retrieved via a call to function: GetData()

CStringData* GetData() const throw()
{
    return( reinterpret_cast< CStringData* >( m_pszData )-1 );
}

The above code is bit of pointer arithmetic, first m_pszData is cast to a pointer to CStringData and then the casted type is deducted by –1 (which will equate to -sizeof(CStringData). So lets see while debugging if we can get to the CStringData located at a negative offset. First lets get the size of ATL::CStringData in memory.

0:045> ?? sizeof(ATL::CStringData)
unsigned int 0x10

Size of ATL::CStringData comes to 0×10 bytes. So in my test application lets find out what is located at a negative offset of 0×10 bytes. In my current frame I’ve the following locals. My CString object is called TestCString, highlighted in bold in the below code snippet.

0:000> dv
           this = 0x00ef6ba8
        cmdInfo = class CCommandLineInfo
       ttParams = class CMFCToolTipInfo
      InitCtrls = struct tagINITCOMMONCONTROLSEX
   pDocTemplate = 0xcccccccc
    TestCString = class ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t> > > 
     pMainFrame = 0xcccccccc

Deduction of 0×10 bytes from address of m_pszData (0x00dfa2f8) gives us the address: 00dfa2e8

0:000> ? 0x00dfa2f8-0x10
Evaluate expression: 14656232 = 00dfa2e8

Lets try dumping out CStringData located at the address: 00dfa2e8. See below

0:000> dt 00dfa2e8 TestStack!ATL::CStringData
   +0x000 pStringMgr       : 0x786cb8e4 ATL::IAtlStringMgr
   +0x004 nDataLength      : 0n23
   +0x008 nAllocLength     : 0n23
   +0x00c nRefs            : 0n1

Dump type says, length of string is: 0n23 which is correct. The length of string “Nibu is testing CString” is indeed 23.

Code documentation of CStringData says this about its member variables…

struct CStringData
{
    IAtlStringMgr* pStringMgr;  // String manager for this CStringData
    int nDataLength;  // Length of currently used data in XCHARs (not including terminating null)
    int nAllocLength;  // Length of allocated data in XCHARs (not including terminating null)
    long nRefs;     // Reference count: negative == locked
    // XCHAR data[nAllocLength+1]  // A CStringData is always followed in memory by the actual array of character data

Difference between nDataLength and nAllocLength is quite evident from the above documentation. Hope this helps.

Share
Nov 052013
 
Share

Recently had a customer who was complaining about high memory usage on Windows 8.1. The application consumed about 140 MB on a Windows 8.1 OS as compared to a meager 3 to 4 MB on a Windows 7 or 8 machine.

Hmm interesting. Being experienced in troubleshooting for sometime now this smelled to me like an issue with some kind of debug flag settings. So immediately checked with customer if he has accidently left some GFlags setting configured.

Reminded me of a customer who had an issue wherein all the application on his box started showing high memory usage, eventually this turned out to be an issue with a system wide flag configured via GFlags. GFlags is a helpful tool but please do remember to undo the changes once you’re done with the debugging. Probably stick a sticky somewhere which will hint you to turn off these settings.

So coming back to this incident, hmm why would the application consume high memory on Windows 8.1. Note: He had the application compiled using VS2008.

Checked memory dump of Test.exe running on Windows 8.1 in our debugger and saw that it has some heap validation features enabled. This is the reason why huge amount of memory is being consumed since these heap validation features will require extra memory.

0:000> !heap
Index   Address  Name      Debugging options enabled
  1:   00300000                 tail checking free checking validate parameters
  2:   00c20000                 tail checking free checking validate parameters
  3:   00200000                 tail checking free checking validate parameters
  4:   02170000                 tail checking free checking validate parameters

I was bit surprised as the customer said he doesn’t have GFlags on his box. So I renamed Test.exe to Test1.exe and this is what the dump shows now. Looks like someone’s enabling heap validation flags on Test.exe.

0:000> !heap
Index   Address  Name      Debugging options enabled
  1:   001d0000                
  2:   00c20000                
  3:   02220000                
  4:   00390000

The application memory usage, after renaming, came down to 3.5 MB.

image

Eventually we figured out who’s turning the heap validation flags on. The integrated Application Verifier included in the Visual Studio Team Suite and Visual Studio Team System for Developers versions of Visual Studio was turning these features on and that was expected as well. The customer had pro version hence he probably didn’t see the settings in project properties. This is how the project property pages will look like…

image

So if you have application verified standalone application installed on your box you’ll see your application listed there as Visual Studio turns certain registry settings on/off based on your settings. Once your application starts up these settings will take effect. Troubleshooting is fun isn’t it. Smile

Share
Oct 232013
 
Share

A customer recently asked this question, thought I’ll share the solution out here. Its not that obvious FYI. When creating an MFC MDI application we have an option to enable tabbed view of MDI documents. Once this is done here’s how the application will look like…

imageimage

image

Note that except for the first sample image you have multiple tab groups in the rest of the screenshots , this is an inbuilt facility provided by the tabbing framework of MFC. This is important when selecting a tab programmatically: You’ll also have to decide which tab from which group you would like to select.

In MFC framework tab groups are represented by CMDIClientAreaWnd::GetMDITabGroups() which returns a member variable of type CObList. This is how the code looks like…

const CObList& GetMDITabGroups() const { return m_lstTabbedGroups; }

This is a list of tab controls. Each tab control in this group denotes a tab group. So when activating a tab we’ll have to decide which tab in a tab group should be activated.

Following sample code activates the first tab in all the tab groups. Please note tab index starts at zero.

void CMainFrame::OnViewActivatetab()
{
    const CObList& TabGrps = m_wndClientArea.GetMDITabGroups();
    for (POSITION pos = TabGrps.GetHeadPosition(); pos != 0;)
    {
        CMFCTabCtrl* pNextWnd = DYNAMIC_DOWNCAST(CMFCTabCtrl, TabGrps.GetNext(pos));
        pNextWnd->ActivateMDITab(1);
    }
}
Share
Oct 172013
 
Share

Some useful links…

Visual Studio 2013 Available Now!
Visual Studio 2013 Highlights
System Requirements and Platform Compatibility
Known issues for Visual Studio 2013 (Readme)
Known issues for .NET Framework 4.5.1 (Readme)
Known issues for Visual Studio Team Foundation Server 2013 (Readme)
Windows Store is now open for submitting apps targeting Windows 8.1

Share