EntryPointNotFoundException Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Исключение, которое возникает при попытке загрузить класс сбоем из-за отсутствия метода записи.
public ref class EntryPointNotFoundException : TypeLoadException
public class EntryPointNotFoundException : TypeLoadException
[System.Serializable]
public class EntryPointNotFoundException : TypeLoadException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class EntryPointNotFoundException : TypeLoadException
type EntryPointNotFoundException = class
inherit TypeLoadException
[<System.Serializable>]
type EntryPointNotFoundException = class
inherit TypeLoadException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type EntryPointNotFoundException = class
inherit TypeLoadException
Public Class EntryPointNotFoundException
Inherits TypeLoadException
- Наследование
- Атрибуты
Комментарии
Исключение EntryPointNotFoundException возникает, когда среда CLR не может загрузить сборку, так как она не может определить точку входа сборки. Это исключение можно вызвать в следующих условиях:
Среда CLR не может найти точку входа приложения (обычно
Mainметод) в исполняемой сборке. Точка входа приложения должна быть глобальной или методом, который не имеет параметров илиstaticстроковый массив в качестве его единственного параметра. Точка входа может возвращатьvoidили возвращать Int32 код выхода UInt32 . Сборка приложения не может определить несколько точек входа.Вызов функции в библиотеке DLL Windows не может быть разрешен, так как не удается найти функцию. В следующем примере создается исключение, EntryPointNotFoundException так как User32.dll не включает функцию с именем
GetMyNumber.using System; using System.Runtime.InteropServices; public class Example { [DllImport("user32.dll")] public static extern int GetMyNumber(); public static void Main() { try { int number = GetMyNumber(); } catch (EntryPointNotFoundException e) { Console.WriteLine("{0}:\n {1}", e.GetType().Name, e.Message); } } } // The example displays the following output: // EntryPointNotFoundException: // Unable to find an entry point named 'GetMyNumber' in DLL 'User32.dll'.open System open System.Runtime.InteropServices [<DllImport "user32.dll">] extern int GetMyNumber() try let number = GetMyNumber() () with :? EntryPointNotFoundException as e -> printfn $"{e.GetType().Name}:\n {e.Message}" // The example displays the following output: // EntryPointNotFoundException: // Unable to find an entry point named 'GetMyNumber' in DLL 'User32.dll'.Module Example Declare Auto Function GetMyNumber Lib "User32.dll" () As Integer Public Sub Main() Try Dim number As Integer = GetMyNumber() Catch e As EntryPointNotFoundException Console.WriteLine("{0}:{2} {1}", e.GetType().Name, e.Message, vbCrLf) End Try End Sub End Module ' The example displays the following output: ' EntryPointNotFoundException: ' Unable to find an entry point named 'GetMyNumber' in DLL 'User32.dll'.Вызов функции в библиотеке DLL Windows не может быть разрешен, так как имя, используемое в вызове метода, не соответствует имени, найденного в сборке. Часто это происходит из-за того, что DllImportAttribute.ExactSpelling поле неявно или явно задано
true, вызываемое метод включает один или несколько строковых параметров и имеет как ANSI, так и версию Юникода, а имя, используемое в вызове метода, не соответствует имени этой версии ANSI или Юникода. В следующем примере показана иллюстрация, пытающаяся вызвать функцию WindowsMessageBoxв User32.dll. Так как первое определение метода указывает CharSet.Unicode для маршалинга строк, общий язык ищет версию функции с широкими символами, а не имя,MessageBoxWиспользуемое в вызове метода.MessageBoxВторое определение метода исправляет эту проблему, вызываяMessageBoxWее вместоMessageBoxфункции.using System; using System.Runtime.InteropServices; public class Example { [DllImport("user32.dll", CharSet = CharSet.Unicode, ExactSpelling = true )] public static extern int MessageBox(IntPtr hwnd, String text, String caption, uint type); [DllImport("user32.dll", CharSet = CharSet.Unicode, ExactSpelling = true )] public static extern int MessageBoxW(IntPtr hwnd, String text, String caption, uint type); public static void Main() { try { MessageBox(new IntPtr(0), "Calling the MessageBox Function", "Example", 0); } catch (EntryPointNotFoundException e) { Console.WriteLine("{0}:\n {1}", e.GetType().Name, e.Message); } try { MessageBoxW(new IntPtr(0), "Calling the MessageBox Function", "Example", 0); } catch (EntryPointNotFoundException e) { Console.WriteLine("{0}:\n {1}", e.GetType().Name, e.Message); } } }open System open System.Runtime.InteropServices [<DllImport("user32.dll", CharSet = CharSet.Unicode, ExactSpelling = true )>] extern int MessageBox(IntPtr hwnd, String text, String caption, uint ``type``) [<DllImport("user32.dll", CharSet = CharSet.Unicode, ExactSpelling = true )>] extern int MessageBoxW(IntPtr hwnd, String text, String caption, uint ``type``) try MessageBox(IntPtr 0, "Calling the MessageBox Function", "Example", 0u) |> ignore with :? EntryPointNotFoundException as e -> printfn $"{e.GetType().Name}:\n {e.Message}" try MessageBoxW(IntPtr 0, "Calling the MessageBox Function", "Example", 0u) |> ignore with :? EntryPointNotFoundException as e -> printfn $"{e.GetType().Name}:\n {e.Message}"Module Example Declare Unicode Function MessageBox Lib "User32.dll" Alias "MessageBox" ( ByVal hWnd As IntPtr, ByVal txt As String, ByVal caption As String, ByVal typ As UInteger) As Integer Declare Unicode Function MessageBox2 Lib "User32.dll" Alias "MessageBoxW" ( ByVal hWnd As IntPtr, ByVal txt As String, ByVal caption As String, ByVal typ As UInteger) As Integer Public Sub Main() Try MessageBox(IntPtr.Zero, "Calling the MessageBox Function", "Example", 0 ) Catch e As EntryPointNotFoundException Console.WriteLine("{0}:{2} {1}", e.GetType().Name, e.Message, vbCrLf) End Try Try MessageBox2(IntPtr.Zero, "Calling the MessageBox Function", "Example", 0 ) Catch e As EntryPointNotFoundException Console.WriteLine("{0}:{2} {1}", e.GetType().Name, e.Message, vbCrLf) End Try End Sub End ModuleВы пытаетесь вызвать функцию в библиотеке динамических ссылок с помощью простого имени, а не его украшенного имени. Как правило, компилятор C++ создает украшенное имя для функций DLL. Например, следующий код C++ определяет функцию, именуемую в библиотеке с именем
DoubleTestDll.dll.__declspec(dllexport) int Double(int number) { return number * 2; }Когда код в следующем примере пытается вызвать функцию, создается исключение, EntryPointNotFoundException так как
Doubleне удается найти функцию.using System; using System.Runtime.InteropServices; public class Example { [DllImport("TestDll.dll")] public static extern int Double(int number); public static void Main() { Console.WriteLine(Double(10)); } } // The example displays the following output: // Unhandled Exception: System.EntryPointNotFoundException: Unable to find // an entry point named 'Double' in DLL '.\TestDll.dll'. // at Example.Double(Int32 number) // at Example.Main()open System open System.Runtime.InteropServices [<DllImport "TestDll.dll">] extern int Double(int number) printfn $"{Double 10}" // The example displays the following output: // Unhandled Exception: System.EntryPointNotFoundException: Unable to find // an entry point named 'Double' in DLL '.\TestDll.dll'. // at Example.Double(Int32 number) // at Example.Main()Module Example Public Declare Function DoubleNum Lib ".\TestDll.dll" Alias "Double" _ (ByVal number As Integer) As Integer Public Sub Main() Console.WriteLine(DoubleNum(10)) End Sub End Module ' The example displays the following output: ' Unhandled Exception: System.EntryPointNotFoundException: Unable to find an ' entry point named 'Double' in DLL '.\TestDll.dll'. ' at Example.Double(Int32 number) ' at Example.Main()Однако если функция вызывается с помощью декорированного имени (в данном случае
?Double@@YAHH@Z), вызов функции завершается успешно, как показано в следующем примере.using System; using System.Runtime.InteropServices; public class Example { [DllImport("TestDll.dll", EntryPoint = "?Double@@YAHH@Z")] public static extern int Double(int number); public static void Main() { Console.WriteLine(Double(10)); } } // The example displays the following output: // 20open System open System.Runtime.InteropServices [<DllImport("TestDll.dll", EntryPoint = "?Double@@YAHH@Z")>] extern int Double(int number) printfn $"{Double 10}" // The example displays the following output: // 20Module Example Public Declare Function DoubleNum Lib ".\TestDll.dll" Alias "?Double@@YAHH@Z" _ (ByVal number As Integer) As Integer Public Sub Main() Console.WriteLine(DoubleNum(10)) End Sub End Module ' The example displays the following output: ' 20Вы можете найти украшенные имена функций, экспортированных библиотекой DLL, с помощью программы, например Dumpbin.exe.
Вы пытаетесь вызвать метод в управляемой сборке, как если бы она была неуправляемой динамической библиотекой ссылок. Чтобы увидеть это в действии, скомпилируйте следующий пример в сборку с именем StringUtilities.dll.
using System; public static class StringUtilities { public static String SayGoodMorning(String name) { return String.Format("A top of the morning to you, {0}!", name); } }module StringUtilities let SayGoodMorning name = $"A top of the morning to you, %s{name}!"Module StringUtilities Public Function SayGoodMorning(name As String) As String Return String.Format("A top of the morning to you, {0}!", name) End Function End ModuleЗатем скомпилируйте и выполните следующий пример, который пытается вызвать
StringUtilities.SayGoodMorningметод в библиотеке динамических ссылок StringUtilities.dll, как если бы это был неуправляемый код. Результатом является EntryPointNotFoundException исключение.using System; using System.Runtime.InteropServices; public class Example { [DllImport("StringUtilities.dll", CharSet = CharSet.Unicode )] public static extern String SayGoodMorning(String name); public static void Main() { Console.WriteLine(SayGoodMorning("Dakota")); } } // The example displays the following output: // Unhandled Exception: System.EntryPointNotFoundException: Unable to find an entry point // named 'GoodMorning' in DLL 'StringUtilities.dll'. // at Example.GoodMorning(String& name) // at Example.Main()open System open System.Runtime.InteropServices [<DllImport("StringUtilities.dll", CharSet = CharSet.Unicode )>] extern String SayGoodMorning(String name) printfn $"""{SayGoodMorning "Dakota"}""" // The example displays the following output: // Unhandled Exception: System.EntryPointNotFoundException: Unable to find an entry point // named 'GoodMorning' in DLL 'StringUtilities.dll'. // at Example.GoodMorning(String& name) // at Example.Main()Module Example Declare Unicode Function GoodMorning Lib "StringUtilities.dll" ( ByVal name As String) As String Public Sub Main() Console.WriteLine(SayGoodMorning("Dakota")) End Sub End Module ' The example displays the following output: ' Unhandled Exception: System.EntryPointNotFoundException: Unable to find an entry point ' named 'GoodMorning' in DLL 'StringUtilities.dll'. ' at Example.GoodMorning(String& name) ' at Example.Main()Чтобы исключить исключение, добавьте ссылку на управляемую сборку и получите доступ
StringUtilities.SayGoodMorningк методу так же, как и к любому другому методу в управляемом коде, как показано в следующем примере.using System; public class Example { public static void Main() { Console.WriteLine(StringUtilities.SayGoodMorning("Dakota")); } } // The example displays the following output: // A top of the morning to you, Dakota!printfn $"""{StringUtilities.SayGoodMorning "Dakota"}""" // The example displays the following output: // A top of the morning to you, Dakota!Module Example Public Sub Main() Console.WriteLine(StringUtilities.SayGoodMorning("Dakota")) End Sub End Module ' The example displays the following output: ' A top of the morning to you, Dakota!Вы пытаетесь вызвать метод в COM-библиотеке DLL, как если бы это была библиотека DLL Windows. Чтобы получить доступ к библиотеке DLL COM, выберите параметр Add Reference в Visual Studio, чтобы добавить ссылку на проект, а затем выберите библиотеку типов на вкладке COM.
Список начальных значений свойств для экземпляра EntryPointNotFoundExceptionсм. в конструкторах EntryPointNotFoundException.
Конструкторы
| Имя | Описание |
|---|---|
| EntryPointNotFoundException() |
Инициализирует новый экземпляр класса EntryPointNotFoundException. |
| EntryPointNotFoundException(SerializationInfo, StreamingContext) |
Устаревшие.
Инициализирует новый экземпляр EntryPointNotFoundException класса сериализованными данными. |
| EntryPointNotFoundException(String, Exception) |
Инициализирует новый экземпляр EntryPointNotFoundException класса с указанным сообщением об ошибке и ссылкой на внутреннее исключение, которое является причиной этого исключения. |
| EntryPointNotFoundException(String) |
Инициализирует новый экземпляр EntryPointNotFoundException класса с указанным сообщением об ошибке. |
Свойства
| Имя | Описание |
|---|---|
| Data |
Возвращает коллекцию пар "ключ-значение", которые предоставляют дополнительные пользовательские сведения об исключении. (Унаследовано от Exception) |
| HelpLink |
Возвращает или задает ссылку на файл справки, связанный с этим исключением. (Унаследовано от Exception) |
| HResult |
Возвращает или задает HRESULT, закодированное числовое значение, назначенное определенному исключению. (Унаследовано от Exception) |
| InnerException |
Exception Возвращает экземпляр, вызвавшего текущее исключение. (Унаследовано от Exception) |
| Message |
Возвращает сообщение об ошибке для этого исключения. (Унаследовано от TypeLoadException) |
| Source |
Возвращает или задает имя приложения или объекта, вызывающего ошибку. (Унаследовано от Exception) |
| StackTrace |
Возвращает строковое представление непосредственных кадров в стеке вызовов. (Унаследовано от Exception) |
| TargetSite |
Возвращает метод, который вызывает текущее исключение. (Унаследовано от Exception) |
| TypeName |
Возвращает полное имя типа, вызывающего исключение. (Унаследовано от TypeLoadException) |
Методы
| Имя | Описание |
|---|---|
| Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
| GetBaseException() |
При переопределении в производном классе возвращает Exception первопричину одного или нескольких последующих исключений. (Унаследовано от Exception) |
| GetHashCode() |
Служит хэш-функцией по умолчанию. (Унаследовано от Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Устаревшие.
SerializationInfo Задает объект с именем класса, именем метода, идентификатором ресурса и дополнительными сведениями об исключении. (Унаследовано от TypeLoadException) |
| GetType() |
Возвращает тип среды выполнения текущего экземпляра. (Унаследовано от Exception) |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| ToString() |
Создает и возвращает строковое представление текущего исключения. (Унаследовано от Exception) |
События
| Имя | Описание |
|---|---|
| SerializeObjectState |
Устаревшие.
Происходит при сериализации исключения для создания объекта состояния исключения, содержащего сериализованные данные об исключении. (Унаследовано от Exception) |