I want to use a C# exe to dynamically load dll that build by C# or C++, the C++ dll part is done, but C# dll not yet done because exe can not find the method in C# dll.
here is my C# dll code that will build a CSharp.dll:
namespace NamespaceName
{
public class ClassName
{
static public double MethodName(string input)
{
Console.WriteLine(input);
Console.Read();
return 0;
}
}
}
here is my C# exe code:
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;
}
}
}
If I'm loading Cpp.dll, the if ((int)intPtr == 0)
will be false, and loading CSharp.dll will be true, so I'm guessing I need to edit string FuncName = "NamespaceName@ClassName@MethodName";
to something else. How can I fix this?