来自 C# 的 gcc DLL:Windows 10 上的"DLL initialization routine failed"

gcc DLL from C#: "DLL initialization routine failed" on Windows 10

本文关键字:DLL 上的 initialization failed routine Windows gcc 来自      更新时间:2023-10-16

我正在开发C#dll,它需要我作为C DLL的代码,由GCC构建。为此,我写了一个C包装器,并使用GCC(TDM-GCC MINGW-W64)作为DLL进行了编译。换句话说,我有:

  • C++.dll由GCC构建;加上使用DLL的C++_test.exe,所以我知道它有效。
  • C.dll由GCC构建,调用C++.dll;加上使用DLL ...
  • C_test.exe
  • C#.dll由Visual Studio构建,调用C.dll;加上C#_test.exe

整个链构建为64位代码。

我的问题是,虽然此设置在我的旧Windows 7框上运行良好,但在带有Windows 10的新计算机上(以及较新版本的软件和库),C#_test.exe在调用C.dll的函数的时候失败,以下消息:Unable to load DLL 'C.dll': A dynamic link library (DLL) initialization routine failed. (Exception from HRESULT: 0x8007045A)

在C#代码中,该函数定义为:

    [DllImport("C.dll", CallingConvention = CallingConvention.Cdecl)]
    private static extern int pg_generate(..);

我在同一文件夹中都有所有其他DLL(否则我会收到有关丢失DLL的另一个错误消息)。

任何想法如何找出问题是什么以及如何解决?我知道这可能有助于在VS中构建整个链,但是我没有所需的项目文件,并且还会构建几个c 。dll取决于的库,所以我宁愿避免这种情况 - 尤其是因为它以前起作用。..

更新:当我在VS中调试C#_test.exe时,它会从pg_generate()抛出:Exception thrown at 0x000000006E0436B0 (C++.dll) in C#_test.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFB64927F5.

更新2:当我使用C#_test.exe(和所有依赖关系)时,我也会遇到相同的错误(DLL初始化例程失败)。这表明问题是在Windows 10中与Windows 7。(这也意味着,一旦客户端升级到Windows 10,我们提供的代码将停止工作...)

我也有同样的问题。事实证明,它的来源是新的/删除操作员。一旦我实施了自己的运营商,应用程序都可以正常工作。对于第三方libs,这并不容易!

这是重现错误在内的最小示例,包括解决方法(如果定义了AddNewOperator,则将定义operator new[],并且结果.dll可以正常工作):

test.cs(与Visual Studio 2017一起编译/运行):

using System;
using System.Runtime.InteropServices;
class Program
{
    [DllImport("libTest", CallingConvention = CallingConvention.StdCall, ExactSpelling = true)]
    public static extern int TestFunction();
    static void Main(string[] args)
    {
        Console.WriteLine("!!" + TestFunction());
    }
}

test.cpp用mingw编译:

#include <new>
#include <cstdlib>
#ifdef AddNewOperator // This will fix the issue
void* operator new[](std::size_t sz){
    return std::malloc(sz);
}
#end
extern "C" {
int __stdcall __declspec(dllexport) TestFunction() {
        int* test = new int[3]; // removing this line will make everything work when building
        return test[2];
}

这是构建脚本:

# Remove the following # and the compiled dll will work just fine
g++ -g -s -Wall -c -fmessage-length=0 Test.cpp  #-DAddNewOperator
g++ -g -shared -o libTest.dll *.o -Wl,--subsystem,windows