C# 在C中从DLL运行代码时出错#
我似乎无法克服这个错误,所以我想知道我的调用代码或DLL中是否有任何错误 -错误-C# 在C中从DLL运行代码时出错#,c#,visual-studio,dll,dllimport,C#,Visual Studio,Dll,Dllimport,我似乎无法克服这个错误,所以我想知道我的调用代码或DLL中是否有任何错误 -错误- $exception {System.BadImageFormatException: The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018) -呼叫码- Assembly assembly = Assembly.LoadFile(@"C:\Users\Admin\Docume
$exception {System.BadImageFormatException: The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018)
-呼叫码-
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代码-
#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;
}
#包括
使用名称空间std;
外部“C”\u declspec(dllexport)void\u stdcall HelloWorld(LPSTR标题,LPSTR消息)
{
MessageBox(空,消息,标题,MB_OK);
}
BOOL APICENT DllMain(模块HMODULE,
德沃德·乌尔打电话的理由,
LPVOID lpReserved
)
{
开关(ul\u呼叫原因\u)
{
案例DLL\u进程\u附加:
案例DLL\u线程\u连接:
案例DLL\u线程\u分离:
案例DLL\u进程\u分离:
打破
}
返回TRUE;
}
Assembly.LoadFile
只能用于加载.NET程序集,而您正在尝试加载普通的.DLL。为了从.NET调用dll中的方法,需要使用P/Invoke。尝试将以下声明添加到类中:
[DllImport("myDll.dll")]
static extern void HelloWorld(string title, string msg);
然后像调用任何其他.NET方法一样调用它。
Assembly.LoadFile
只能用于加载.NET程序集,而您正在尝试加载普通的.DLL。为了从.NET调用dll中的方法,需要使用P/Invoke。尝试将以下声明添加到类中:
[DllImport("myDll.dll")]
static extern void HelloWorld(string title, string msg);
然后像调用任何其他.NET方法一样调用它。首先,我认为您的后期绑定调用是错误的,应该是:
obj.InvokeMember("NameOfYouyMethod",
BindingFlags.Default | BindingFlags.InvokeMethod,
null, obj, new object[] { YourParameters );
如果你真的想通过后期绑定做到这一点,也可以查看博客
正如其他人指出的那样,使用p/Invoke。首先,我认为您的后期绑定调用是错误的,应该是:
obj.InvokeMember("NameOfYouyMethod",
BindingFlags.Default | BindingFlags.InvokeMethod,
null, obj, new object[] { YourParameters );
如果你真的想通过后期绑定做到这一点,也可以查看博客
正如其他人所指出的,请使用p/Invoke。非常感谢,先生。:>非常感谢,先生。:>