[英]Unable to Call Simple Custom Dll Import from C# Application
更新資料
我現在已經完成了3次相同的結果(Visual Studio / Windows無法將DLL識別為有效文件)。 這一定是我所處環境的問題,因為下面的Mike遍歷了本教程,並且工作正常。
我上次運行時確實在C ++項目的解決方案資源管理器中注意到了這一點:
有誰知道這還好嗎? 似乎有很多紅色停車標志,對我來說,這表明事情很糟糕。
在學習完本教程之后,我得出了以下結論:
C#
using System.Runtime.InteropServices;
namespace TestImport
{
class Program
{
[DllImport("TestLib.dll")]
public static extern void DisplayHelloFromDLL();
static void Main(string[] args)
{
DisplayHelloFromDLL();
}
}
}
C ++
.cpp
文件中的Source Files
#include <stdio.h>
extern "C"
{
__declspec(dllexport) void DisplayHelloFromDLL()
{
printf("Hello from DLL !\n");
}
}
在Visual Studio中進行調試時:
An unhandled exception of type 'System.DllNotFoundException' occurred in TestImport.exe
Additional information: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
當運行內置的EXE時(從與DLL相同的文件夾中):
An attempt was made to load a program with an incorrect format.
我在上述代碼中做錯了什么嗎? 我在VS 2015中完成了所有這些工作,在該教程中,VS 2010要求使用該教程,但是我找不到最新的教程。
當我嘗試通過“ Project -> Add Reference ...
我看到此錯誤:
A reference to 'Path\To\MyLib.dll' could not be added. Please make sure
that the file is accessible, and that it is a valid assembly or COM
component.
這使我認為問題出在源代碼或DLLs配置上。
我還嘗試過構建兩個文件並將它們放置在運行Executable之前的相同文件夾中,但是沒有任何改善的結果(與運行上面的EXE時相同的錯誤)。
解決方案資源管理器截圖:
確保C ++項目的名稱和DllImport參數相同。 另外,如果dll
文件與C#項目不在同一目錄中,請確保將dll
添加到Debug/Release
文件夾中。
也! 編譯時,請確保您以相同的32/64位模式運行。.如果您使用32位編譯dll並嘗試在64位C#程序中使用它,則它將無法正常工作。
OK,現在構建此應用程序,然后將先前構建的DLL復制到當前應用程序的Debug / Release目錄中 。 DLL應與您的主應用程序位於同一目錄中。
您是否以粗體顯示文字? 默認情況下,您的C#應用程序不知道在哪里尋找DLL,並且它會在build文件夾中查找。
類型為“ System.DllNotFoundException”的未處理異常
它發生在我身上,因為導入了c ++ dll,所以缺少了自己的依賴dll。
將它們復制到Debug / Release文件夾后,一切正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.