I can't seem to get past this error, so I'm wondering if I'm doing anything wrong in my call code, or my DLL?
-Error-
$exception  {System.BadImageFormatException: The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018)
-call code-
 Assembly assembly = Assembly.LoadFile(@"C:\Users\Admin\Documents\Visual Studio 2012\Projects\MyDLL\Release\myDLL.dll");
            Type type = assembly.GetType("HelloWorld");
            var obj = Activator.CreateInstance(type);
            // Alternately you could get the MethodInfo for the TestRunner.Run method
            type.InvokeMember("HelloWorld",
                              BindingFlags.Default | BindingFlags.InvokeMethod,
                              null,
                              obj,
                              null);
-DLL code-
#include <Windows.h>
using namespace std;
extern "C" _declspec(dllexport) void __stdcall HelloWorld(LPSTR title, LPSTR msg)
{
   MessageBox( NULL, msg, title, MB_OK);
}
BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}
Assembly.LoadFile can only be used to load .NET assemblies, whereas you're attempting to load a plain .DLL. You'll need to use P/Invoke in order to call the method within your dll from .NET. Try adding the following declaration you your class:
[DllImport("myDll.dll")]
static extern void HelloWorld(string title, string msg);
Then calling it as you would any other .NET method.
First of all I think your late binding call is wrong, it should be:
obj.InvokeMember("NameOfYouyMethod", 
                 BindingFlags.Default | BindingFlags.InvokeMethod, 
                 null, obj, new object[] { YourParameters );
Also check the blog here if you want to really do this via late binding.
Also as others have pointed out use P/Invoke.
User contributions licensed under CC BY-SA 3.0