我正在使用以下 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# 反射”以找到许多解释其工作原理的资源。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句