关于C#调用VC++ DLL

由于在C#调用VC的DLL文件不能直接引用,那么,我们可以通过以下办法解决。

DLL文件分为托管和非托管,在调用托管的很好办,直接被使用的需要引用,间接使用的需要拷贝到bin目录下.非托管的处理会比较麻烦,实际上,你拷贝到bin没有任何帮助,因为CLR会把文件拷贝到一个临时目录下,然后在那运行web,而CLR只会拷贝托管文件,这就是为什么我们明明把非托管的dll放在了bin下却依然提示不能加载模块了.那么,就可以直接放在system32的目录下,或者自己重新建个文件夹。

调用DLL中的方法

首先,应该在C#语言源程序中声明外部方法,其基本形式是:

[DLLImport("DLL文件")]

修饰符extern返回变量类型方法名称(参数列表)

如:

        /// <summary>
/// 解密字符串
/// </summary>
/// <param name="strDeciphering">需要解密的字符串</param>
/// <returns>返回解密后的字符串</returns>
[DllImport("desdll.dll", EntryPoint = "Desec", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
public static extern string deciphering(string strDeciphering);

/// <summary>
/// 解密字符串
/// </summary>
/// <param name="strDec">需要解密的字符串</param>
/// <returns>返回解密的字符串</returns>
public string GetDeciphering(string strDec)
{
return deciphering(strDec);
}

对于 DllImport  必须在方法的前面(具体参考MSDN),EntryPoint  = "Desec" 表示DLL内的函数名(写错了会提示找不到 入口)。在 deciphering(string strDeciphering) 中的参数表示函
数的需要的参数。

只有需要用的时候直接调用
GetDeciphering(string strDec) 方法即可。
posted @ 2011-07-25 16:49  月夜清风  阅读(4472)  评论(0编辑  收藏  举报