本文介绍C# call C++的dll的使用方法
首先根据注册表键获取想要加载的dll的路径
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FTAStubUtility.GetRegistryValue
{
public class GetRegistry
{
//strHKLMProduce:去除HKLM部分
public static string getKeyValue(string strHKLMProduce,string keys)
{
string strProductDirectory = string.Empty;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(strHKLMProduce.Replace("HKLM\\","")))
{
if (null != key)
{
object value = key.GetValue(keys);
if (null != value)
{
strProductDirectory = value.ToString();
}
}
}
return strProductDirectory;
}
}
}
根据dll路径动态设置dllimport的路径(调用SetDllDirectory),并导入dll,实现相关方法,需要注意的是加载完dll之后需要释放dll(调用UnloadImportedDll)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace FTAStubUtility.Assem
{
public class LoadStub
{
[DllImport("test.dll")] //import dll,实现这个dll的test函数
extern static internal int test();
[DllImport("kernel32", SetLastError = true)]
private static extern bool FreeLibrary(IntPtr hModule);
public static void UnloadImportedDll(string DllPath)
{
foreach (System.Diagnostics.ProcessModule mod in System.Diagnostics.Process.GetCurrentProcess().Modules)
{
if (mod.FileName == DllPath)
{
FreeLibrary(mod.BaseAddress);
}
}
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetDllDirectory(string lpPathName);
}
}
To set more than one additional DLL search path, modify the PATH environment variable, e.g.:
static void AddEnvironmentPaths(string[] paths)
{
string path = Environment.GetEnvironmentVariable("PATH") ?? string.Empty;
path += ";" + string.Join(";", paths);
Environment.SetEnvironmentVariable("PATH", path);
}
详细demo
using FTAStubUtility.Assem;
using FTAStubUtility.StartService;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FTAStubUtility
{
class Program
{
/// <summary>
/// args[0]:regKey
/// args[1]:regValue
/// </summary>
/// <param name="args"></param>
static int Main(string[] args)
{
if (args.Length == 2)
{
try
{
string installPath = GetRegistryValue.GetRegistry.getKeyValue(args[0].ToString(), args[1].ToString());
LoadStub.SetDllDirectory(installPath);
//Directory.SetCurrentDirectory(installPath);
int dlltype = LoadStub.test();
LoadStub.UnloadImportedDll(Path.Combine(installPath, "test.dll"));
Console.WriteLine(dlltype);
return dlltype;
}
catch (Exception ex)
{
Console.WriteLine(-1);
return -1;
}
}
else
{
Console.WriteLine(-1);
return -1;
}
}
}
}