我有一个 C# 表单应用程序...我创建了一个 Dll...现在我想使用这个程序启动那个 dll。我该怎么做?
#include <windows.h>
typedef int (*function1_ptr) ();
function1_ptr function1=NULL;
int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, int) {
HMODULE myDll = LoadLibrary("Dll1.dll");
if(myDll!=NULL) {
function1 = (function1_ptr) GetProcAddress(myDll,"function1");
if(function1!=NULL)
function1();
else
exit(4);
FreeLibrary(myDll);
}
else
exit(6);
GetLastError();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是用于测试我的 dll 的代码......即 Dll1.dll..function1
是dll1.dll中的函数......我可以用 C# 代码做类似的事情吗???
要执行代码示例的操作,请使用以下 C# 代码:
public static class DllHelper
{
[System.Runtime.InteropServices.DllImport("Dll1.dll")]
public static extern int function1();
}
private void buttonStart_Click(object sender, EventArgs e)
{
try
{
DllHelper.function1();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
上面的示例是一个 C# 程序,它调用非基于 .NET 的 DLL 中的函数。下面的示例是一个 C# 程序,它调用基于 .NET 的 DLL 中的函数。
try
{
System.Reflection.Assembly dll1 = System.Reflection.Assembly.LoadFile("Dll1.dll");
if (dll1 != null)
{
object obj = dll1.CreateInstance("Function1Class");
if (obj != null)
{
System.Reflection.MethodInfo mi = obj.GetType().GetMethod("function1");
mi.Invoke(obj, new object[0]);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Run Code Online (Sandbox Code Playgroud)
这两个例子中的任何一个是你想要的吗?或者您是否尝试从示例代码中调用 DLL 中的 C# 函数?