Calling function from ComImport class doesn't fail as expected - c#

I'm trying to verify that the class I'm trying to use via COM works as expected. Unfortunately it seems to succeed on a call which should fail:
enum X509CertificateEnrollmentContext
{
ContextUser = 0x1,
ContextMachine = 0x2,
ContextAdministratorForceMachine = 0x3
}
[ComImport(), Guid("884e2045-217d-11da-b2a4-000e7bbb2b09")]
class Cenroll { }
[Guid("728ab35d-217d-11da-b2a4-000e7bbb2b09")]
interface IX509CertificateRequestCmc2
{
void InitializeFromTemplate(
[In] X509CertificateEnrollmentContext Context,
[In] IX509EnrollmentPolicyServer pPolicyServer,
[In] IX509CertificateTemplate pTemplate);
}
static void Main(string[] args)
{
var cr = new Cenroll();
var cmc2 = (IX509CertificateRequestCmc2)cr;
cmc2.InitializeFromTemplate(X509CertificateEnrollmentContext.ContextUser, null, null);
}
Casting from Cenroll to the interface works, which indicates that the guids are ok. (and it fails casting to other guids, so it's not random success)
But when I call InitializeFromTemplate, with both parameters set to null, it succeeds. The documentation says that the result should be an E_POINTER error:
Return code - Description
E_POINTER - The pPolicyServer and pTemplate parameters cannot be NULL.
So why don't I see an exception?

The problem is that you are redeclaring the interface, and the new definition is different from the original.
Guids are OK, but underneath, QueryInterface implementation checks GUID, and returns the pointer to the implementation - this is the interface vtable and method addresses are calculated relative to this address (when a call to the method is compiled, offset of the method is added to this address to get the actuall address).
In your implementation, InitializeFromTemplate is the first method and generated client code calls the method at the beginning of vtable.
However, in the original interface, there are 56 other methods before InitializeFromTemplate because there is an inheritance chain:
IX509CertificateRequest (25 methods)
|
+-> IX509CertificateRequestPkcs7 (8 methods)
|
+-> IX509CertificateRequestCmc (23 methods)
|
+-> IX509CertificateRequestCmc2
Function addresses in the certenroll.dll adhere to this layout, so when you call InitializeFromTemplate as declared in your interface, you are calling the first method in chain which is actually IX509CertificateRequest::Initialize.
As an experiment, if you add 56 dummy methods before InitializeFromTemplate in your IX509CertificateRequestCmc2 you will correctly receive an exception:
[Guid("728ab35d-217d-11da-b2a4-000e7bbb2b09")]
interface IX509CertificateRequestCmc
{
void fn1();
void fn2();
...
void fn56();
void InitializeFromTemplate(...);
}
The call will throw: CertEnroll::CX509CertificateRequestCmc::InitializeFromTemplate: Invalid pointer 0x80004003 (-2147467261)
Of course, the solution is not to add the dummy methods :) You should use the generated interop types instead of providing your own. As you are referencing the certenroll assembly, I don't understand why don't you simply use those generated interop classes. Here's the full example which behaves as expected:
using CERTENROLLLib;
namespace comcerttest
{
class Program
{
static void Main(string[] args)
{
// If you are embedding the interop types, note that you must
// remove the `Class` suffix from generated type name in order
// to instantiate it. See link at the bottom for explanation:
var cr = new CX509CertificateRequestCmc();
var cmc2 = (IX509CertificateRequestCmc2)cr;
cmc2.InitializeFromTemplate(X509CertificateEnrollmentContext.ContextUser, null, null);
}
}
}
The issue with using class vs interface type is explained here:
Using embedded interop types

Related

How to get .net managed method pointer by "MethodName" that can be called on native code [duplicate]

This question already has answers here:
C# GetDelegateForFunctionPointer with generic delegate
(6 answers)
Closed 2 years ago.
Precondition
The .net method that I will get its pointer is:
public static method
have no overloads
arguments and return value just ValueType (unsafe pointer, primitive type, unmanaged struct)
Reason
Get the method pointer so I can call in C++ program.
This works for me but I need to declare delegate for every method.
I want to get rid of doing things over and over again.
In .net side:
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void UpdateDelegate(float delta);
public static void* GetUpdatePointer()
{
var delegateInstance = = new UpdateDelegate(Update);
var pfnUpdate = Marshal.GetFunctionPointerForDelegate(delegateInstance);
return (void*)pfnUpdate;
}
public static Update(float delta)=>{...}
In C++ side:
typedef void (_stdcall * FuncPtr)(float);
void foo()
{
//just pseudo-code showing where is the pfnUpdate from.
FuncPtr pfnUpdate = (FuncPtr)GetUpdatePointer();
pfnUpdate(0.01f);
}
what I want
In c#, I export GetMethodPointer for my native code. It will return a function pointer to specified method, and this pointer can be invoked by native program via stdcall calling convention.
//avoid gc collect this object
static List<Delegate> KeepReference = new List<Delegate>();
public unsafe static void* GetMethodPointer(string name)
{
System.Reflection.MethodInfo methodInfo = typeof(PhysicsMain).GetMethod(name);
// also mark this delegate with [UnmanagedFunctionPointer(CallingConvention.StdCall)] attribute
Type delegateType = ConstructDelegateTypeWithMethodInfo(methodInfo);
var delegateInstance = Delegate.CreateDelegate(delegateType, methodInfo);
KeepReference.Add(delegateInstance);
return (void*)Marshal.GetFunctionPointerForDelegate(delegateInstance);
}
I need ConstructDelegateTypeWithMethodInfo to create a delegate with the same signature as the specified method. And mark [UnmanagedFunctionPointer(CallingConvention.StdCall)] attribute for it so that can be marshaled as a function pointer.
I think it may using IL, Reflection, even Asm to do this. Or using IL to write the whole GetMethodPointer method.
Finally, I got a solution these days. Firstly, I came across Expression.GetDelegateType given by this post. But it did't work for me, because Marshal.GetFunctionPointerForDelegate doesn't support generic delegate type generate by Expression.GetDelegateType. I thought there might be a clue in implementation of Expression.GetDelegateType. So, I browsed referencesource and got a internal method called MakeNewCustomDelegate. This link gives code about how to call the internal method. Things are readily solved!
Edit: I forgot to say, the default unmanaged calling convension of a delegate is stdcall, so we don't need to mark the delegate with [UnmanagedFunctionPointer(CallingConvention.StdCall)] explicitly.
In your example you assume that the class of the method is know function (PhysicsMain).
If UpdateDelegate is also known you can use it easily:
Type delegateType = typeof(UpdateDelegate);
var delegateInstance = Delegate.CreateDelegate(delegateType, methodInfo);
But you can also get this type by name only:
Type delegateType = Type.GetType("Namespace.ClassName+UpdateDelegate");
var delegateInstance = Delegate.CreateDelegate(delegateType, methodInfo);
You can look at delegateType.CustomAttributes and verify that the type has UnmanagedFunctionPointer attribute.

ResolveMethod() Returning Completely Different Method

I was resolving methods from .NET DLLs, and noticed that the method being returned by Module.ResolveMethod() is completely different from original method. I am specifying the method's exact MetadataToken, so it makes absolutely no sense to me why I would end up with anything else but the original method.
In the below example, I have the 'Dispose()' method. I grab its metadata token and resolve it, only to find that I now have the 'OnBackColorChanged(System.EventArgs)'method
static void Main(string[] args)
{
Assembly assembly = Assembly.LoadFrom(#"C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Windows.Forms.dll");
MethodInfo method = assembly.GetModules()[0].GetTypes()[300].GetMethods()[362];
Console.WriteLine(method); //Returns 'Void Dispose()'
MethodInfo method2 = (MethodInfo)assembly.GetModules()[0].ResolveMethod(method.MetadataToken);
Console.WriteLine(method2); //Returns 'Void OnBackColorChanged(System.EventArgs)' ...why?
}
Button, through long inheritance chain, inherits from Component class, which implements IDisposable and has void Dispose() method. This is the method you obtain via
assembly.GetModules()[0].GetTypes()[300].GetMethods()[362];
Since this method is declared on type Component, which is located in System assembly - no surprise that using its metadata handle to resolve method from completely different module (System.Windows.Forms) leads to random results.
If you want to get only methods declared on this concrete type - use BindingFlags.DeclaredOnly:
var allMethods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
But note this will return only methods declared on Button, not on any parent type, even if that parent type belongs to the same module.
Alternatively - filter by module:
Assembly assembly = Assembly.LoadFrom(#"C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Windows.Forms.dll");
var module = assembly.GetModules()[0];
var type = module.GetTypes()[300];
var allMethods = type.GetMethods().Where(c => c.Module == module).ToArray();

Can I use reflection with RealProxy instances?

I'm quite sure I'm missing some constraint or caveat somewhere, but here's my situation. Assume I have a class that I want to have a proxy for, like the following:
public class MyList : MarshalByRefObject, IList<string>
{
private List<string> innerList;
public MyList(IEnumerable<string> stringList)
{
this.innerList = new List<string>(stringList);
}
// IList<string> implementation omitted for brevity.
// For the sake of this exercise, assume each method
// implementation merely passes through to the associated
// method on the innerList member variable.
}
I want to create a proxy for that class, so that I can intercept method calls and perform some processing on the underlying object. Here is my implementation:
public class MyListProxy : RealProxy
{
private MyList actualList;
private MyListProxy(Type typeToProxy, IEnumerable<string> stringList)
: base(typeToProxy)
{
this.actualList = new MyList(stringList);
}
public static object CreateProxy(IEnumerable<string> stringList)
{
MyListProxy listProxy = new MyListProxy(typeof(MyList), stringList);
object foo = listProxy.GetTransparentProxy();
return foo;
}
public override IMessage Invoke(IMessage msg)
{
IMethodCallMessage callMsg = msg as IMethodCallMessage;
MethodInfo proxiedMethod = callMsg.MethodBase as MethodInfo;
return new ReturnMessage(proxiedMethod.Invoke(actualList, callMsg.Args), null, 0, callMsg.LogicalCallContext, callMsg);
}
}
Finally, I have a class that consumes the proxied class, and I set the value of the MyList member via reflection.
public class ListConsumer
{
public MyList MyList { get; protected set; }
public ListConsumer()
{
object listProxy = MyListProxy.CreateProxy(new List<string>() { "foo", "bar", "baz", "qux" });
PropertyInfo myListPropInfo = this.GetType().GetProperty("MyList");
myListPropInfo.SetValue(this, listProxy);
}
}
Now, if I try to use reflection to access the proxied object, I run into problems. Here is an example:
class Program
{
static void Main(string[] args)
{
ListConsumer listConsumer = new ListConsumer();
// These calls merely illustrate that the property can be
// properly accessed and methods called through the created
// proxy without issue.
Console.WriteLine("List contains {0} items", listConsumer.MyList.Count);
Console.WriteLine("List contents:");
foreach(string stringValue in listConsumer.MyList)
{
Console.WriteLine(stringValue);
}
Type listType = listConsumer.MyList.GetType();
foreach (Type interfaceType in listType.GetInterfaces())
{
if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(ICollection<>))
{
// Attempting to get the value of the Count property via
// reflection throws an exception.
Console.WriteLine("Checking interface {0}", interfaceType.Name);
System.Reflection.PropertyInfo propInfo = interfaceType.GetProperty("Count");
int count = (int)propInfo.GetValue(listConsumer.MyList, null);
}
else
{
Console.WriteLine("Skipping interface {0}", interfaceType.Name);
}
}
Console.ReadLine();
}
}
Attempting to call GetValue on the Count property via reflection throws the following exception:
An exception of type 'System.Reflection.TargetException' occurred in
mscorlib.dll but was not handled in user code
Additional information: Object does not match target type.
When attempting to get the value of the Count property, apparently the framework is calling down into System.Runtime.InteropServices.WindowsRuntime.IVector to call the get_Size method. I'm not understanding how this call fails on the underlying object of the proxy (the actual list) to make this happen. If I'm not using a proxy of the object, getting the property value works fine via reflection. What am I doing wrong? Can I even do what I'm trying to accomplish?
Edit: A bug has been opened regarding this issue at the Microsoft Connect site.
I think this may be a bug in the .Net framework. Somehow the RuntimePropertyInfo.GetValue method is picking the wrong implementation for the ICollection<>.Count property, and it appears to have to do with WindowsRuntime projections. Perhaps the remoting code was redone when they put the WindowsRuntime interop in the framework.
I switched the framework to target .Net 2.0 since I thought if this was a bug, it shouldn't be in that framework. When converting, Visual Studio removed the "Prefer 32 bit" check on my console exe project (since this doesn't exist in 2.0). It runs without exception when this is not present.
In summary, it runs on .Net 2.0 in both 32 and 64 bit. It runs on .Net 4.x in 64 bit. The exception is thrown on .Net 4.x 32 bit only. This sure looks like a bug. If you can run it 64-bit, that would be a workaround.
Note that I've installed .Net 4.6, and this replaces much of the .Net framework v4.x. It could be this is where the problem is introduced; I can't test until I get a machine that doesn't have .Net 4.6.
Update: 2015-09-08
It also happens on a machine with only .Net 4.5.2 installed (no 4.6).
Update: 2015-09-07
Here's a smaller repro, using your same classes:
static void Main(string[] args)
{
var myList = MyListProxy.CreateProxy(new[] {"foo", "bar", "baz", "quxx"});
var listType = myList.GetType();
var interfaceType = listType.GetInterface("System.Collections.Generic.ICollection`1");
var propInfo = interfaceType.GetProperty("Count");
// TargetException thrown on 32-bit .Net 4.5.2+ installed
int count = (int)propInfo.GetValue(myList, null);
}
I've also tried the IsReadOnly property, but it appears to work (no exception).
As to the source of the bug, there are two layers of indirection around properties, one being the remoting, and the other being a mapping of metadata structures called MethodDefs with the actual runtime method, known internally as a MethodDesc. This mapping is specialized for properties (as well as events), where additional MethodDescs to support the property's get/set PropertyInfo instances are known as Associates. By calling PropertyInfo.GetValue we go through one of these Associate MethodDesc pointers to the underlying method implementation, and remoting does some pointer math to get the correct MethodDesc on the other side of the channel. The CLR code is very convoluted here, and I don't have enough experience of the in-memory layout of the MethodTable which holds these MethodDesc records which remoting uses (or the mapping it uses to get to the MethodTable?), but I'd say it's a fair guess that remoting is grabbing the wrong MethodDesc via some bad pointer math. That's why we see a similar but unrelated (as far as your program) MethodDesc - UInt32 get_Size of IVector<T> being invoked on the call:
System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
ConsoleApplication1.MyListProxy.Invoke(IMessage msg) Program.cs: line: 60
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
System.Runtime.InteropServices.WindowsRuntime.IVector`1.get_Size()
System.Runtime.InteropServices.WindowsRuntime.VectorToCollectionAdapter.Count[T]()
This is a pretty interesting CLR bug, some of its guts are showing in the mishap. You can tell from the stack trace that it is trying to call the VectorToCollectionAdapter's Count property.
This class is rather special, no instance of it ever gets created. It is part of the language projection that was added in .NET 4.5 that makes WinRT interface types look like .NET Framework types. It is pretty similar to the SZArrayHelper class, an adapter class that helps implement the illusion that non-generic arrays implement generic interface types like IList<T>.
The interface mapping at work here is for the WinRT IVector<T> interface. As noted in the MSDN article, that interface type is mapped to IList<T>. The internal VectorToListAdapter class takes care of the IList<T> members, VectorToCollectionAdapter tackles the ICollection<T> members.
Your code forces the CLR to find the implementation of ICollection<>.Count and that could either be a .NET class implementing it as normal or it could be a WinRT object that exposes it as IVector<>.Size. Clearly the proxy you created gives it a headache, it incorrectly decided for the WinRT version.
How it is supposed to figure out which is the correct choice is pretty murky. After all, your proxy could be a proxy for an actual WinRT object and then the choice it made would be correct. This could well be a structural problem. That it acts so randomly, the code does work in 64-bit mode, is not exactly inspiring. VectorToCollectionAdapter is very dangerous, note the JitHelpers.UnsafeCast calls, this bug is potentially exploitable.
Well, alert the authorities, file a bug report at connect.microsoft.com. Let me know if you don't want to take the time and I'll take care of it. A workaround is hard to come by, using the WinRT-centric TypeInfo class to do the reflection did not make any difference. Removing the jitter forcing so it runs in 64-bit mode is a band-aid but hardly a guarantee.
we are currently hacking around this problem with this brittle intervention (apologies for code):
public class ProxyBase : RealProxy
{
// ... stuff ...
public static T Cast<T>(object o)
{
return (T)o;
}
public static object Create(Type interfaceType, object coreInstance,
IEnforce enforce, string parentNamingSequence)
{
var x = new ProxyBase(interfaceType, coreInstance, enforce,
parentNamingSequence);
MethodInfo castMethod = typeof(ProxyBase).GetMethod(
"Cast").MakeGenericMethod(interfaceType);
return castMethod.Invoke(null, new object[] { x.GetTransparentProxy() });
}
public override IMessage Invoke(IMessage msg)
{
IMethodCallMessage methodCall = (IMethodCallMessage)msg;
var method = (MethodInfo)methodCall.MethodBase;
if(method.DeclaringType.IsGenericType
&& method.DeclaringType.GetGenericTypeDefinition().FullName.Contains(
"System.Runtime.InteropServices.WindowsRuntime"))
{
Dictionary<string, string> methodMap = new Dictionary<string, string>
{ // add problematic methods here
{ "Append", "Add" },
{ "GetAt", "get_Item" }
};
if(methodMap.ContainsKey(method.Name) == false)
{
throw new Exception("Unable to resolve '" + method.Name + "'.");
}
// thanks microsoft
string correctMethod = methodMap[method.Name];
method = m_baseInterface.GetInterfaces().Select(
i => i.GetMethod(correctMethod)).Where(
mi => mi != null).FirstOrDefault();
if(method == null)
{
throw new Exception("Unable to resolve '" + method.Name +
"' to '" + correctMethod + "'.");
}
}
try
{
if(m_coreInstance == null)
{
var errorMessage = Resource.CoreInstanceIsNull;
WriteLogs(errorMessage, TraceEventType.Error);
throw new NullReferenceException(errorMessage);
}
var args = methodCall.Args.Select(a =>
{
object o;
if(RemotingServices.IsTransparentProxy(a))
{
o = (RemotingServices.GetRealProxy(a)
as ProxyBase).m_coreInstance;
}
else
{
o = a;
}
if(method.Name == "get_Item")
{ // perform parameter conversions here
if(a.GetType() == typeof(UInt32))
{
return Convert.ToInt32(a);
}
return a;
}
return o;
}).ToArray();
// this is where it barfed
var result = method.Invoke(m_coreInstance, args);
// special handling for GetType()
if(method.Name == "GetType")
{
result = m_baseInterface;
}
else
{
// special handling for interface return types
if(method.ReturnType.IsInterface)
{
result = ProxyBase.Create(method.ReturnType, result, m_enforce, m_namingSequence);
}
}
return new ReturnMessage(result, args, args.Length, methodCall.LogicalCallContext, methodCall);
}
catch(Exception e)
{
WriteLogs("Exception: " + e, TraceEventType.Error);
if(e is TargetInvocationException && e.InnerException != null)
{
return new ReturnMessage(e.InnerException, msg as IMethodCallMessage);
}
return new ReturnMessage(e, msg as IMethodCallMessage);
}
}
// ... stuff ...
}
m_coreInstance here is the object instance that the proxy is wrapping.
m_baseInterface is the interface the object is to be used as.
this code intercepts the call(s) made in VectorToListAdapter and VectorToCollectionAdapter and converts it back into the original via that methodMap dictionary.
the part of the conditional:
method.DeclaringType.GetGenericTypeDefinition().FullName.Contains(
"System.Runtime.InteropServices.WindowsRuntime")
makes sure it only intercepts calls that come from stuff in the System.Runtime.InteropServices.WindowsRuntime namespace - ideally we would target the types directly but they are inaccessible - this should probably be changed to target specific class names in the namespace.
the parameters are then cast into the appropriate types and the method is invoked. the parameter conversions appear to be necessary as the incoming parameter types are based on the parameter types of the method calls from the objects in the System.Runtime.InteropServices.WindowsRuntime namespace, and not the parameters of the method calls to the original object types; i.e. the original types before the objects in the System.Runtime.InteropServices.WindowsRuntime namespace hijacked the mechanism.
for example, the WindowsRuntime stuff intercepts the original call to get_Item, and converts it into a call to the Indexer_Get method: http://referencesource.microsoft.com/#mscorlib/system/runtime/interopservices/windowsruntime/vectortolistadapter.cs,de8c78a8f98213a0,references. this method then calls the GetAt member with a different parameter type, which then calls GetAt on our object (again with a different parameter type) - this is the call we hijack in our Invoke() and convert it back into the original method call with the original parameter types.
it would be nice to be able to reflect over VectorToListAdapter and VectorToCollectionAdapter to extract all their methods and the nested calls they make, but these classes are unfortunately marked as internal.
this works for us here, but i'm sure its full of holes - it is a case of trial and error, running it to see what fails and then adding in the required dictionary entries/parameter conversions. we are continuing the search for a better solution.
HTH

Why does adding beforefieldinit drasticly improve the execution speed of generic classes?

I'm working on a proxy and for generic classes with a reference type parameter it was very slow. Especially for generic methods (about 400 ms vs 3200 ms for trivial generic methods that just returned null). I decided to try to see how it would perform if I rewrote the generated class in C#, and it performed much better, about the same performance as my non-generic class code.
Here is the C# class I wrote:: (note I changed by naming scheme but not a heck of a lot)::
namespace TestData
{
public class TestClassProxy<pR> : TestClass<pR>
{
private InvocationHandler<Func<TestClass<pR>, object>> _0_Test;
private InvocationHandler<Func<TestClass<pR>, pR, GenericToken, object>> _1_Test;
private static readonly InvocationHandler[] _proxy_handlers = new InvocationHandler[] {
new InvocationHandler<Func<TestClass<pR>, object>>(new Func<TestClass<pR>, object>(TestClassProxy<pR>.s_0_Test)),
new GenericInvocationHandler<Func<TestClass<pR>, pR, GenericToken, object>>(typeof(TestClassProxy<pR>), "s_1_Test") };
public TestClassProxy(InvocationHandler[] handlers)
{
if (handlers == null)
{
throw new ArgumentNullException("handlers");
}
if (handlers.Length != 2)
{
throw new ArgumentException("Handlers needs to be an array of 2 parameters.", "handlers");
}
this._0_Test = (InvocationHandler<Func<TestClass<pR>, object>>)(handlers[0] ?? _proxy_handlers[0]);
this._1_Test = (InvocationHandler<Func<TestClass<pR>, pR, GenericToken, object>>)(handlers[1] ?? _proxy_handlers[1]);
}
private object __0__Test()
{
return base.Test();
}
private object __1__Test<T>(pR local1) where T:IConvertible
{
return base.Test<T>(local1);
}
public static object s_0_Test(TestClass<pR> class1)
{
return ((TestClassProxy<pR>)class1).__0__Test();
}
public static object s_1_Test<T>(TestClass<pR> class1, pR local1) where T:IConvertible
{
return ((TestClassProxy<pR>)class1).__1__Test<T>(local1);
}
public override object Test()
{
return this._0_Test.Target(this);
}
public override object Test<T>(pR local1)
{
return this._1_Test.Target(this, local1, GenericToken<T>.Token);
}
}
}
This is compiles in release mode to the same IL as my generated proxy here is the class that its proxying::
namespace TestData
{
public class TestClass<R>
{
public virtual object Test()
{
return default(object);
}
public virtual object Test<T>(R r) where T:IConvertible
{
return default(object);
}
}
}
There was one-exception, I was not setting the beforefieldinit attribute on the type generated. I was just setting the following attributes::public auto ansi
Why did using beforefieldinit make the performance improve so much?
(The only other difference was I wasn't naming my parameters which really didn't matter in the grand scheme of things.
The names for methods and fields are scrambled to avoid collision with real methods.
GenericToken and InvocationHandlers are implementation details that are irrelevant for sake of argument.
GenericToken is literally used as just a typed data holder as it allows me to send "T" to the handler
InvocationHandler is just a holder for the delegate field target there is no actual implementation detail.
GenericInvocationHandler uses a callsite technique like the DLR to rewrite the delegate as needed to handle the different generic arguments passed
)
EDIT::
Here is the test harness::
private static void RunTests(int count = 1 << 24, bool displayResults = true)
{
var tests = Array.FindAll(Tests, t => t != null);
var maxLength = tests.Select(x => GetMethodName(x.Method).Length).Max();
for (int j = 0; j < tests.Length; j++)
{
var action = tests[j];
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
{
action();
}
sw.Stop();
if (displayResults)
{
Console.WriteLine("{2} {0}: {1}ms", GetMethodName(action.Method).PadRight(maxLength),
((int)sw.ElapsedMilliseconds).ToString(), j);
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
private static string GetMethodName(MethodInfo method)
{
return method.IsGenericMethod
? string.Format(#"{0}<{1}>", method.Name, string.Join<Type>(",", method.GetGenericArguments()))
: method.Name;
}
And in a test I do the following::
Tests[0] = () => proxiedTestClass.Test();
Tests[1] = () => proxiedTestClass.Test<string>("2");
Tests[2] = () => handClass.Test();
Tests[3] = () => handClass.Test<string>("2");
RunTests(100, false);
RunTests();
Where Tests is a Func<object>[20], and proxiedTestClass is the class generated by my assembly, and handClass is the one I generated by hand.
RunTests is called twice, once to "warm" things up, and again to run it and print to the screen. I mostly took this code from a post here by Jon Skeet.
As stated in ECMA-335 (CLI cpecification), part I, section 8.9.5:
The semantics of when and what triggers execution of such type
initialization methods, is as follows:
A type can have a type-initializer method, or not.
A type can be specified as having a relaxed semantic for its type-initializer method (for convenience below, we call this relaxed
semantic BeforeFieldInit).
If marked BeforeFieldInit then the type’s initializer method is executed at, or sometime before, first access to any static field
defined for that type.
If not marked BeforeFieldInit then that type’s initializer method is executed at (i.e., is triggered by):
a. first access to any static field of that type, or
b. first invocation of any static method of that type, or
c. first invocation of any instance or virtual method of that type
if it is a value type or
d. first invocation of any constructor for that type.
Also, as you can see from the Michael's code above, the TestClassProxy has only one static field: _proxy_handlers. Notice, that it is used only two times:
In the instance constructor
And in the static field initializer itself
So when BeforeFieldInit is specified, type-initializer will be called only once: in the instance constructor, right before the first access to _proxy_handlers.
But if BeforeFieldInit is omitted, CLR will place the call to the type-initializer before every TestClassProxy's static method invocation, static field access, etc.
In particular, the type-initializer will be called on every invocation of s_0_Test and s_1_Test<T> static methods.
Of course, as stated in ECMA-334 (C# Language Specification), section 17.11:
The static constructor for a non-generic class executes at most once
in a given application domain. The static constructor for a generic
class declaration executes at most once for each closed constructed
type constructed from the class declaration (§25.1.5).
But in order to guarantee this, CLR have to check (in a thread-safe manner) if the class is already initialized, or not.
And these checks will decrease the performance.
PS: You might be surprised that performance issues will gone once you change s_0_Test and s_1_Test<T> to be instance-methods.
First, if you want to learn more about beforefieldinit, read Jon Skeet's article C# and beforefieldinit. Parts of this answer are based on that and I'll repeat the relevant bits here.
Second, your code does very little, so overhead will have significant impact on your measurements. In real code, the impact is likely to be much smaller.
Third, you don't need to use Reflection.Emit to set whether a class has beforefieldint. You can disable that flag in C# by adding a static constructor (e.g. static TestClassProxy() {}).
Now, what beforefieldinit does is that it governs when is the type initializer (method called .cctor) called. In C# terms, type initializer contains all static field initializers and code from the static constructor, if there is one.
If you don't set that flag, the type initializer will be called when either an instance of the class is created or any of the static members of the class are referenced. (Taken from the C# spec, using CLI spec here would be more accurate, but the end result is the same.*)
What this means is that without beforefieldinit, the compiler is very confined about when to call the type initializer, it can't decide to call it a bit earlier, even if doing that would be more convenient (and resulted in faster code).
Knowing this, we can look at what's actually happening in your code. The problematic cases are static methods, because that's where the type initializer might be called. (Instance constructor is another one, but you're not measuring that.)
I focused on the method s_1_Test(). And because I don't actually need it to do anything, I simplified it (to make the generated native code shorter) to:
public static object s_1_Test<T>(TestClass<pR> class1, pR local1) where T:IConvertible
{
return null;
}
Now, let's look at the disassembly in VS (in Release mode), first without the static constructor, that is with beforefieldinit:
00000000 xor eax,eax
00000002 ret
Here, the result is set to 0 (it's done in somewhat obfuscated manner for performance reasons) and the method returns, very simple.
What happens with static the static constructor (i.e. without beforefieldinit)?
00000000 sub rsp,28h
00000004 mov rdx,rcx
00000007 xor ecx,ecx
00000009 call 000000005F8213A0
0000000e xor eax,eax
00000010 add rsp,28h
00000014 ret
This is much more complicated, the real problem is the call instruction, which presumably calls a function that invokes the type initializer if necessary.
I believe this the source of the performance difference between the two situations.
The reason why the added check is necessary is because your type is generic and you're using it with a reference type as a type parameter. In that case, the JITted code for different generic versions of your class is shared, but the type initializer has to be called for each generic version. Moving the static methods to another, non-generic type would be one way to solve the issue.
* Unless you do something crazy like calling instance method on null using call (and not callvirt, which throws for null).

Invoking Method on Object Instantiated From DLL

I am having some trouble with assemblies and DLL's.
instrument_ is declared as an object and I'm creating an instance of "PP150" from the dll whose path is specified by path_.
string className = ContineoProperties.getSingleton().getClassName(path_);
assembly_ = Assembly.LoadFrom(path_);
Type classType = assembly_.GetType("Instrument." + className);
instrument_ = Activator.CreateInstance(classType);
Later I to call the method isntrument_.instrumentCommand(cmd.getCommandName())
The error I get is with when i call the method.
'object' does not contain a definition for 'instrumentCommand'
The isntrument_ is created fine. its just the method call that's giving me a problem. The method does exist in the "PP150.dll". Do I need some DLLImport to allow it to recognize it as a function?
Thanks,
P
If object type is not known in compile time,
To call a method defined on an object, you must use Reflection.
MethodInfo mInfo = classType.GetMethod("instrumentCommand");
mInfo.Invoke(instrument_, new Object[] { _parameters});
The compiler is never going to recognize the methods on a type that you are loading via reflection (e.g. using Assembly.GetType() and Activator.CreateInstance()). Unless you have the type metadata available at build time, you will always get that error if you try to call methods that are not defined on Object itself.
You have two options for making that kind of method call. Both of them require you to give up type safety, the only difference is the amount of work required. In both cases, if you make a mistake, the compiler will not tell you -- you will get a runtime exception instead.
Declare instrument_ as dynamic instead of object. This, obviously, only works in .NET 4.0, but it accomplishes exactly what you're trying to do. The method call will be dispatched at runtime, so as long as the instance that instrument_ references actually has a method call with the appropriate name, it will work.
Use reflection to call the method. You're already using reflection to load the type, so you are halfway there. You would need to add something like this:
// The array of types is the parameter list; assuming instrumentCommand takes
// a string it would look like this:
MethodInfo method = classType.GetMethod("instrumentCommand", new Type[] { typeof(string) });
method.Invoke(instrument_, new object[] { cmd.getCommandName() });
This happens because Activator.CreateInstance returns an object. I would create a separate DLL for the interface which is implemented by the class you want to instantiate. Both the DLL containing this class, and the executable should reference the DLL containing the interface. This way you could cast the object returned by Activator.CreateInstance to the interface, and call its methods:
IInstrument.dll:
interface IInstrument
{
void instrumentCommand(string cmd);
}
Instrument.dll (add IInstrument.dll as reference):
class Instrument : IInstrument
{
public void instrumentCommand(string cmd)
{
// ... implementation ...
}
}
InstrumentApp.exe (add IInstrument.dll as reference):
class Program
{
public static void Main()
{
// ... load Instrument.dll into assembly object ...
// ... load the type from the assembly ...
IInstrument instrument_ = (IInstrument)Activator.CreateInstance(classType);
instrument_.instrumentCommand(cmd.getCommandName());
}
}
The most simple thing would be to link agains PP150.
If you did link against the dll you must use Assembly.LoadFile or Assembly.Load and not LoadFrom because the last one will cause the assembly load to load your assembly in the LoadFrom loader context which will alter type identity.
Suppose you load the Type T from Assembly A via LoadFrom and you link against A as well.
object CreateTypeFrom()
{
var A = Assembly.LoadFrom(#"xxxx");
return A.CreateInstance("T");
}
void Test()
{
object t = CreateTypeFrom();
T RealT = new T(); // no prob
T Castedt = (T)t; // this will throw an InvalidCastException
T isNull = t as T; // this will result in a null instance
}
As you can see although you did create two times an instance of T they cannot be casted to due to different loader context which will make the type pretty useless.
To get rid of these things you could simply use Reflection to create a proxy type which will forward your calls to the proxy type. If you are using .NET 4 you can take advantage of the DLR to find the best matching methods at runtime. The code below creats a Version object and returns it as dynamic object. Then I do call the Major property to an integer and print it out to console. This does work with no exceptions nor compile time errors if you are using .NET 4 or later.
dynamic CreateTypeFrom()
{
var assembly = typeof(string).Assembly;
return assembly.CreateInstance("System.Version", true, BindingFlags.CreateInstance, null, new object[] { 1, 2, 3, 4 }, null, null);
}
[TestMethod]
public void Test()
{
var t = CreateTypeFrom();
int major = t.Major;
Console.WriteLine(major);
}

Categories