簡體   English   中英

Windows 10上來自C#的gcc DLL:“ DLL初始化例程失敗”

[英]gcc DLL from C#: “DLL initialization routine failed” on Windows 10

我正在開發需要由gcc構建的C#DLL所需代碼的C#DLL。 為此,我編寫了一個C包裝程序,並使用gcc(TDM-GCC MinGW-w64)作為DLL對其進行了編譯。 換句話說,我有:

  • 由gcc構建的C++.dll 加上使用DLL的C++_test.exe ,所以我知道它可以工作。
  • 由gcc構建的C.dll ,調用C++.dll 加上使用DLL的C_test.exe ...
  • 由Visual Studio構建的C#.dll ,調用C.dll 加上C#_test.exe

整個鏈構建為64位代碼。

我的問題是,雖然此設置在舊的Windows 7機器上運行良好,但在裝有Windows 10的新計算機上(以及較新版本的軟件和庫), C#_test.exe在從C.dll調用函數時失敗C.dll ,並顯示以下消息: Unable to load DLL 'C.dll': A dynamic link library (DLL) initialization routine failed. (Exception from HRESULT: 0x8007045A) 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.C#_test.exe中的Exception thrown at 0x000000006E0436B0 (C++.dll) in C#_test.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFB64927F5.

更新2:當我使用在舊機器上構建和測試的C#_test.exe (以及所有依賴項)時,也遇到相同的錯誤(DLL初始化例程失敗)。 這表明問題出在Windows 10與Windows7。(這也意味着,一旦客戶端升級到Windows 10,我們提供的代碼將停止工作...)

我遇到過同樣的問題。 原來,它的來源是new / delete運算符。 一旦實現了自己的運算符,該應用程序就會正常運行。 對於第三方庫,這並不是那么容易!

這是重現該錯誤的最小示例,其中包括解決方法(如果定義了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());
    }
}

用mingw編譯的Test.cpp:

#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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM