2014-10-30 119 views
2

我一直在用VS2013 Native Tools命令提示符测试一些东西。c#中的BadImageFormatException。预期包含mainfest

到目前为止,我无法让我的代码加载我制作的dll。

这是我的dll代码,用c语言编写。 (基于msdn的例子)

int __declspec(dllexport) SampleMethod(int i){return i*-10;} 

并在VS2013 Native Tools中用cl/LD编译它。

然后,我编译了我的C#代码与CS20 VS2013本机工具。

public class MainClass 
{ 
    static void Main(string[] args) 
    { 
     Assembly assembly; 
     try 
     { 
      assembly = Assembly.Load(args[0]); 
      Console.WriteLine("Loaded dll"); 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine("Exception caught : \n{0}.", e); 
     } 
    }  
} 

而且捕捉到的异常都按:

Exception caught : 
System.BadImageFormatException: Could not load file or assembly 'test' or one of 
its dependencies. The module was expected to contain an assembly manifest. 
File name: 'test' 
    at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String cod 
eBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& 
stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntro 
spection, Boolean suppressSecurityChecks) 
    at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName as 
semblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMar 
k& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIn 
trospection, Boolean suppressSecurityChecks) 
    at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evid 
ence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolea 
n forIntrospection) 
    at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evid 
ence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) 
    at System.Reflection.Assembly.Load(String assemblyString) 
    at MainClass.Main(String[] args) 

我在x86和x64的工具尝试,现在我的想法。

回答

3

Assembly.Load只能加载托管(.NET)程序集。你试图加载一个本地DLL,产生错误。

相反,你想使用P/Invoke。这只适用于普通的C风格的方法,如果你需要处理C++类,您需要首先创建一个互操作库。

的P/Invoke方法对你的情况的签名会是这个样子:

[DllImport("test.dll")] 
public static extern int SampleMethod(int i); 
+0

那我怎么会尝试读取我不知道其他的方法? – revolute 2014-10-30 08:46:01

+0

*那么我将如何尝试阅读其他我不知道的方法?*想必您会以某种方式了解它们。否则,你不会问这个问题... – 2014-10-30 08:47:38

+0

我的意思是看着一个DLL,看看它包含什么方法。某种类型的dll导出查看器。 – revolute 2014-10-30 08:49:34