Error running code from DLL in C#

0

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;
}
c#
visual-studio
dll
dllimport
asked on Stack Overflow Mar 4, 2013 by CyanPrime

2 Answers

4

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.

answered on Stack Overflow Mar 4, 2013 by Iridium
0

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.

answered on Stack Overflow Mar 4, 2013 by Mo Patel • edited Jan 13, 2014 by Mo Patel

User contributions licensed under CC BY-SA 3.0