[英]Calling a C# DLL in a C# program, entry point not found
我正在使用以下 C# DLL。
using System;
namespace LibraryTest
{
public class Class1
{
public int callNr(int nr)
{
if (nr == 5)
{
return 555;
}
return 0;
}
}
}
並在程序中像這樣使用它:
using System;
using System.Runtime.InteropServices;
namespace Builder.Store
{
public class testIndicator : Indicator
{
[DllImport(@"C:\LibraryTest.dll", EntryPoint = "callNr")]
public static extern int callNr(int nr);
public override void Calculate()
{
int value = callNr(5);
//do stuff...
}
}
}
唯一的結果是“無法在 DLL 中找到入口點”錯誤。 我的研究:我的 VS 中沒有 dumpbin,但是我使用了 dotPeek,結果是 DLL 與源代碼匹配。 我使用了 Dependency Walker,DLL 似乎很好,但它沒有指出入口點,附上截圖。
https://i.stack.imgur.com/RR4UH.jpg
我使用的程序是獨立的第三方軟件,它允許自定義文件輸入(我無法向實際程序添加 DLL 引用)。 我不知所措。 任何指針和/或明顯的錯誤?
正如評論中提到的,在與本機代碼交互時使用DllImport
。
要在 .NET Dll 中調用方法,您必須執行以下操作:
// First load the assembly
var assembly = Assembly.LoadFrom(@"C:\LibraryTest.dll");
// Get the type that includes the method you want to call by name (must include namespace and class name)
var class1Typetype = assembly.GetType("LibraryTest.Class1");
// Since your method is not static you must create an instance of that class.
// The following line will create an instance using the default parameterless constructor.
// If the class does not have a parameterless constructor, the following line will faile
var class1Instance = Activator.CreateInstance(class1Typetype);
// Find the method you want to call by name
// If there are multiple overloads, use the GetMethod overload that allows specifying parameter types
var method = class1Typetype.GetMethod("callNr");
// Use method.Invoke to call the method and pass the parameters in an array, cast the result to int
var result = (int)method.Invoke(class1Instance, new object[] { 5 });
這種按名稱調用方法的技術稱為“反射”。 您可以在谷歌上搜索術語“C# 反射”以找到許多解釋其工作原理的資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.