【问题标题】:BadImageFormatException in c#. Expected to contain manifestC# 中的 BadImageFormatException。预计包含清单
【发布时间】:2014-12-26 04:52:50
【问题描述】:

我一直在用 VS2013 Native Tools Command Prompt 测试一些东西。

到目前为止,我无法让我的代码加载我制作的 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 工具,但现在我没有想法了。

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 那我将如何尝试阅读我不知道的其他方法?
    • 那么我将如何尝试阅读我不知道的其他方法? 想必您以某种方式知道它们。否则你不会问这个问题...
    • 我的意思是查看一个 dll 并查看它包含哪些方法。某种 dll 导出查看器。
    • @revolute 是的,这要复杂得多。 P/Invoking 包括编组代码的自动生成,这是您在运行时无法轻松完成的。通过使用适当的DllImports 创建一个动态类可能是可行的,但我从未尝试过。否则,您要么使用 C++/CLI 帮助程序库,要么手动使用各种 LoadLibrary WinAPI 方法(可能是个坏主意)。当然,您总是至少需要方法定义——本机 DLL 不像托管方式那样具有自我描述性。
    • 我想我的旅程会很艰难。我可以找到 dll viewers ,一定有办法。无论如何,谢谢你的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 2013-06-24
    • 2019-09-20
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多