代码改变世界

动态调用c++的dll

2008-03-26 09:03  Virus-BeautyCode  阅读(701)  评论(2编辑  收藏  举报
是我在论坛看到的一个例子,所以记录下来,以后用到可以参考。
[
DllImport(
"Kernel32.dll")
]
public static extern int LoadLibrary(String funcname);

[
DllImport(
"Kernel32.dll")
]
public static extern int GetProcAddress(int handle, String funcname);

[
DllImport(
"Kernel32.dll")
]
public static extern int FreeLibrary(int handle);

//
// 注意: 参数列表及返回值要与方法(test)对应..
//
public delegate int Invoker(string ProjName, string SchemeName, string Mile, ref double ContnMile, ref bool Reliability, ref short LineKind);

static void Main(string[] args)
{
int handle = LoadLibrary(@"test.dll"); //要调用的类库..

if (handle != 0)
{
int address = GetProcAddress(handle, "test"); //指定函数名称..

if (address != 0)
{
Invoker invoker
= (Invoker)Marshal.GetDelegateForFunctionPointer(new IntPtr(address), typeof(Invoker));

//use invoker -> demo: invoker(...);

FreeLibrary(handle);
}
}
}