c# - C# 中的 BadImageFormatException。预计包含 list

标签 c# interop pinvoke .net-assembly badimageformatexception

我一直在使用 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 工具,但现在我没有主意了。

最佳答案

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

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

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

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

关于c# - C# 中的 BadImageFormatException。预计包含 list ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26648071/

相关文章:

c# - 将 MyDbContext 合并到 Asp.net IdentityDbContext

c# - 从 C++ 使用 COM Interop 对象

c# - 使用 C# P/Invoke 的方法对 Struct 内的数组进行编码

c# - 修改 JavaScript 中的字符串、日期和数字对象

c# - OnTearDown 在 NUnit 测试中未被调用

c# - 如何在字符串中嵌入 Razor 变量?

c# - 使用 .NET 4.0、3.5 时,UnmanagedFunctionPointer 会导致堆栈溢出

c++ - 编码(marshal) C++ 锯齿状数组给出 "Invalid managed/unmanaged type combination"错误

c# - 如何在 C# 中从 C.dll 编码字节*

c# - 如果我的程序正在将 dll 文件复制到临时目录,我是否需要特定权限?