== Loading Managed DLLs or Assemblies ==
Source: [[http://stackoverflow.com/questions/1137781/c-correct-way-to-load-assembly-find-class-and-call-run-method|Correct way to load assembly]]
If you do not have access to the TestRunner type information in the calling assembly (it sounds like you may not), you can call the method like this:
Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
Type type = assembly.GetType("TestRunner");
var obj = Activator.CreateInstance(type);
// Alternately you could get the MethodInfo for the TestRunner.Run method
type.InvokeMember("Run",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
obj,
null);
If you have access to the IRunnable interface type, you can cast your instance to that (rather than the TestRunner type, which is implemented in the dynamically created or loaded assembly, right?):
Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll"); // @ = static string, i.e. no special char interpretation in the following string
Type type = assembly.GetType("TestRunner");
IRunnable runnable = Activator.CreateInstance(type) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();
== Loading Unmanaged DLLs ==
Create a library wrapper to reference from your managed code.
* Import library function signatures. Open a Visual Studio Command Prompt and issue this command: C:\> dumpbin /exports MyLib.dll
This outputs: Dump of file MyLib.dll
File Type: DLL
Section contains the following exports for MyLib.dll
00000000 characteristics
0 time date stamp Wed Dec 31 19:00:00 1969
0.00 version
1 ordinal base
17 number of functions
17 number of names
ordinal hint RVA name
1 0 00010D4C Initialize
2 1 00010D5C ActivateDevice
15 2 000112F8 OpenPort
4 3 00010F94 ClosePort
14 4 000111F4 GetDebugStatus
12 5 0001131C GetFcomVersion
11 6 00010FCC GetNoPollTimeout
17 7 000113B0 GetPortMode
5 8 0001102C GetPortStatus
9 9 00010E98 GetRspArray
13 A 0001133C MaxComPort
3 B 00010ECC OpenPort
8 C 00010E74 RspReady
7 D 00010E40 SendCmdArray
6 E 00010D6C SendReady
10 F 00011004 SetNoPollTimeout
16 10 0001135C SetPortMode
Summary
1000 .edata
1000 .idata
2000 .reloc
2000 .rsrc
2000 BSS
11000 CODE
1000 DATA
* Create wrapper with each function name found with ''dumpbin'' using ''DllImport'': using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace AHI.Testing.Frye
{
public class MyLib_DLL_Wrapper
{
private const String DLL_NAME = "MyLib.dll"; // DLL
[DllImport(DLL_NAME, EntryPoint = "OpenPort")]
public static extern int OpenPort(ref int portNum);
[DllImport(DLL_NAME, EntryPoint = "ClosePort")]
public static extern int ClosePort(ref int portNum);
...
}
}