Dynamicaly load and call a function in Win32 dll

Z

ZhangZQ

Is it possible to dynamicaly to local and call a function in Win32 dll(not a
..net assembly dll) in C# at run time, for example, a C# program popup a
dialogbox to let use input which Win32 dll to be loaded, which function to
be called, and what are the parameters to call the function.


Thank you very much!
 
A

AlexS

Use reflection namespace for defining class and methods using data from your
dialog, compile it, load assembly and call.

HTH
Alex
 
W

Wiktor Zychla

Is it possible to dynamicaly to local and call a function in Win32 dll(not
a
.net assembly dll) in C# at run time, for example, a C# program popup a
dialogbox to let use input which Win32 dll to be loaded, which function to
be called, and what are the parameters to call the function.

a partial solution is to write another Win32 dll that has fixed interface
and can dynamically load and call a function from Win32 library given by
name.

Regards,
Wiktor
 
A

AlexS

You can start from
http://msdn.microsoft.com/library/d...ourcecodecompilingprogramfromcodedomgraph.asp.

It's dynamic compilation topic. If you don't like this way, you can create
source code in any other suitable for you way - as file - and use csc.exe or
vbc.exe to make dll or exe, which will expose Win32 call to .net.

For every Win32 function you want to call in such way you need to know all
the details for DllImport attribute. In simple cases it is just what is the
type of returned result and what are the types of parameters to pass.

E.g. standard wrapper for SetWindowText might look like:

class Win32Wrapper {
public Win32Wrapper() {
[DllImport("User32")]
internal static extern int ShowWindow(IntPtr hWnd, int nCmdShow);
...
public int Execute(IntPtr hWnd, int nCmdShow) {
return ShowWindow(hWnd,nCmdShow);
}
}
}

After you compile this, you can use Reflection to load resulting dll,
instantiate Win32Wrapper and call Execute with your parameters.

The rest is up to you. Which functions you want to define, which calls etc.

You can use similar approach when wrapper assembly is created in C++ 5 or 6,
or even VB6. Older style assemblies will require additional step - check
type library importer - tlbimp.exe. There is description what to do if you
want to change MSIL in assembly even, e.g.
http://msdn.microsoft.com/msdnmag/issues/03/09/netprofilingapi/ - if you
really want to make this toy 100% dynamic and know how to modify IL.

Anyway, I think you should do your homework first. Copy/paste approach here
won't work really. For example, in this sample - how you plan to ask user to
specify hWnd parameter? Did you think about it already?

HTH
Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top