我想使用 C# exe 动态加载由 C# 或 C++ 构建的 dll,C++ dll 部分已完成,但 C# dll 尚未完成,因为 exe 在 C# dll 中找不到方法。
这是我将构建 CSharp.dll 的 C# dll 代码:
namespace NamespaceName
{
public class ClassName
{
static public double MethodName(string input)
{
Console.WriteLine(input);
Console.Read();
return 0;
}
}
}
这是我的 C# exe 代码:
using System;
using System.Runtime.InteropServices;
namespace TestCall
{
class Program
{
[DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
static extern int LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);
[DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
static extern IntPtr GetProcAddress(int hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName);
[DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
static extern bool FreeLibrary(int hModule);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate double MethodName(string a);
static void Main(string[] arg) //pass in string array
{
string DllName = "...Desktop//CSharp.dll"; //would be like: string DllName = ChooseWhatDllToCall();
string FuncName = "NamespaceName@ClassName@MethodName"; //would be like: string FuncName = ChooseWhatFuncToUse();
int hModule = LoadLibrary(DllName);
if (hModule == 0)
return;
IntPtr intPtr;
intPtr = GetProcAddress(hModule, FuncName);
if ((int)intPtr == 0)
{
FreeLibrary(hModule);
return;
}
MethodName run = (MethodName)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(MethodName));
string input = "just a string that will print by dll method";
double result = run(input);
FreeLibrary(hModule);
return;
}
}
}
如果我正在加载 Cpp.dll,if ((int)intPtr == 0)
则将为假,而加载 CSharp.dll 将为真,所以我猜我需要编辑string FuncName = "NamespaceName@ClassName@MethodName";
其他内容。我怎样才能解决这个问题?