c#中的BadImageFormatException。预计包含清单

时间:2014-10-30 08:21:24

标签: c# interop pinvoke .net-assembly badimageformatexception

我一直在使用VS2013 Native Tools命令提示符测试一些内容。

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

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

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

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

然后我用VS2013 Native Tools中的csc编译了我的c#代码。

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工具,现在我已经没想到了。

1 个答案:

答案 0 :(得分:3)

Assembly.Load只能加载托管(.NET)程序集。您正在尝试加载本机DLL,从而产生错误。

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

您案例的P / Invoke方法的签名如下所示:

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