473,587 Members | 2,580 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Return values get lost with Reflection.Emit

Hi there,
I'm currently trying to call some API-Functions via Reflection.Emit since I
need to bind to different dlls based on user input. The dynamic creation of
the required PInvoke-Methods works just fine and when invoked the functions
are executed perfectly well. The only problem is that I seem to be unable to
get back any return values. To simplify the whole case I created a
test-setup that binds to user32.dll, dynamically creates a PInvokeMethod to
call the MessageBox function and invokes that function. Same effect ... the
return value always is 0. Quite impossible to detect which button was
clicked this way :-(
The example provided in the MSDN is not really helpful since it simply
ignores the return value since they a simple OkOnly-MessageBox in contrast
to my Cancel/Retry/Ignore-box.
Anybody out there who can reproduce my scenario or can point me to where I
screwed up? Any help would be greatly appreciated.

Greeting,
Matti

public class Manager
{
AssemblyBuilder assembly;

public Manager()
{
assembly = CreateDLLAccess ();
TestApiCall(ass embly);
}

private AssemblyBuilder CreateDLLAccess ()
{
AppDomain currentDomain;
AssemblyName name;
MethodBuilder method=null;
AssemblyBuilder assembly;
ModuleBuilder module;

// Get the current application domain for the current thread.
currentDomain = AppDomain.Curre ntDomain;
name = new AssemblyName();
name.Name = "TEST";

// Define a dynamic assembly in the 'currentDomain' .
assembly = currentDomain.D efineDynamicAss embly(name,
AssemblyBuilder Access.Run);

// Define a dynamic module in "TEST" assembly.
module = assembly.Define DynamicModule(" ApiWrapper");

// Define a PInvoke method giving the name of the entrypoint in the
dll.
Type[] myType = new Type[] {typeof(int), typeof(string),
typeof(string), typeof(int)};
method = module.DefinePI nvokeMethod("Ms gBox", "user32.dll ",
"MessageBox ", MethodAttribute s.Public | MethodAttribute s.Static |
MethodAttribute s.PinvokeImpl, CallingConventi ons.Standard, typeof(int),
myType,CallingC onvention.Winap i, CharSet.Auto);
module.CreateGl obalFunctions() ;

return assembly;
}

private void TestApiCall(Ass emblyBuilder assembly)
{
Module module = assembly.GetMod ule("ApiWrapper ");
MethodInfo method;
method = module.GetMetho d("MsgBox");
object[] args = new object[] {(int) 0, "a", "b", (int) 0x2};
int i = (int) method.Invoke(n ull, args);
}
}

Whatever I try (fiddling around with Attributes, CallingConventi ons,
dynamically creating a type for the PInvokeMethod and substituting
MethodInfo.Invo ke() with Type.InvokeMeth od() or Type.InvokeMemb er()) i will
always be 0 :-(
Nov 15 '05 #1
1 3034
Hi again,
Mattias Sögren over at framework.inter op just posted the solution which
works absolutely perfect:
Matthias,

You have to set the preservesig metadata flag on the method. For some
reason it defaults to off for DefinePInvokeMe thod, whereas it defaults
to on when you use the DllImport attribute.

method.SetImple mentationFlags( MethodImplAttri butes.PreserveS ig |
method.GetMeth odImplementatio nFlags() );

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.

Nov 15 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
8428
by: samlee | last post by:
Hi All, I'm learning how to write C# using reflection, but don't know how to code using reflection this.Controls.Add(this.label1); Could anyone help, Thank in advance. xxx======================================================================
7
9948
by: Mark Miller | last post by:
I am using Reflection.Emit to dynamically build a class. A method of the class to be built requires a Parameter of type "Type". But I don't know how to use Emit to pass a call of "typeof()" to the method. The method could look like this: public void myDynamicMethod(Type type){ //.....do something with the Type passed in....... }
3
2510
by: John Arthur | last post by:
Hi, I am reading about Reflection.Emit and I can't really imagine a real situation where I can use this. Can someone give me an example that can't be done without Reflection or an example of something that If done with Reflection.Emit will be a lot faster or something sensible. I will really appreciate your help. Thanks : John Arthur
3
3036
by: ayende | last post by:
How do I use Reflection.Emit to produce code similar to this? public void bar<T>() { } public void foo<J>() { bar<J>(); }
2
1647
by: allfyre | last post by:
Ok, to make a long story short, I'm Emitting some MSIL from a c# application. I know that THIS is the MSIL I want to be emitting: //************************************************************** ..method public hidebysig instance class System.Data.SqlClient.SqlCommand Format1(class Delta.DictionaryDispatch dispatch) cil managed { .custom...
0
1546
by: cfatulescu | last post by:
Hello, i'm trying to reproduce a method using Reflection.Emit, everything is going well except one small thing, without all my job is done for nothing. I can not reproduce the keyword "return" and to set it to an attribute by using Reflection.Emit. Help!!!, pls
8
3850
by: =?Utf-8?B?U2hhd24=?= | last post by:
Hi; i just started research reflection and i'm wondering if i have an empty class file can i use reflection to add member variables and attributes dynamically and then instantiate the class? What i would like to be able to do is start with and empty class, then depending on the data provided to me by a config file, add the member variables...
9
4157
by: Michael Sander | last post by:
Hello ng, anyone knowns how to add a reference to an assembly to System.Reflection.AssemblyBuilder? In System.Web.Compilation.AssemblyBuilder is a function like AddAssemblyReference, but not in System.Reflection. Regards, Michael
0
1653
by: =?Utf-8?B?QXJ0dXJvIE1hcnRpbmV6?= | last post by:
I've been looking everywhere on how to call AddRange Method of a List<myClassfield in Reflection.Emit My code goes like this MethodInfo method = typeof(List<>).MakeGenericType(typeof(myClass)).GetMethod("AddRange", BindingFlags.Instance | BindingFlags.Public, null, new Type { typeof(IEnumerable<>).MakeGenericType(typeof(myClass)) },...
0
7918
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7843
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8206
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8340
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6621
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5713
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5392
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3875
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1185
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.