日期:2014-05-18  浏览次数:20396 次

请教C#中调用DLL的一个问题
C# code

//问题是:一运行到下面一句后台代码,便提示:找不到DLL入口函数scan!!!当我在VC++6.0下测试DLL文件,完全正确;当我传前两
//个参数,不传第三个communtiy,也正确,一传communtiy便提示出错,为什么呢?
//C++代码主要部分:
char **scan(char *startip, char *endip,char *community)
{
    char **p=new char*[255];
    int status, first, last, i;
    int sum=0;                //用来统计网段中扫描的IP数目,以在主函数中使用;
    char *c=new char[16];
        ............. 
        ctarget.set_readcommunity(community);  //此处用到形参;
}
//c#调用代码:
namespace docms.DLL
{
    public class oneRouteIpScan
    {
        [DllImport("..\\dllFile\\oneRouteIpScan.dll",
            EntryPoint = "scan",
            CharSet = CharSet.Ansi ,
            CallingConvention = CallingConvention.StdCall)
        ]
        public static extern IntPtr scan(string s1,string s2,string s3);
    }
}
//c#相关后台代码:
 protected void Page_Load(object sender, EventArgs e)
        {
            beginip = this.Request.QueryString["beginIp"].ToString().Trim();
            endip = this.Request.QueryString["endIp"].ToString().Trim();
            community = this.Request.QueryString["community"].ToString().Trim();
            ......................
            IntPtr p = docms.DLL.routeIpScan.scan(beginip, endip,community); 
        }  





------解决方案--------------------
嘿嘿,我遇到过这个问题。

原因是DLL的路径

[DllImport("..\\dllFile\\oneRouteIpScan.dll",
你使用了相对路径,但是哪个路径是local path呢?你如果是winform,当然就是exe所在的路径了。
但你是IIS,那么current directory就是C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

解决办法有几个:
1.使用绝对路径
2. 将oneRouteIpScan.dll放到系统目录
3. 将oneRouteIpScan.dll放到C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727相应的位置。
4. 在静态构造函数中设置path环境变量:
static KioskEngine()
{
// Change the PATH environment variable to include the directory
// where the engine resides.
string kioskEnginePath = Util.KioskEngineDir; //oneRouteIpScan.dll所在的路径
string orgPath = Environment.GetEnvironmentVariable("PATH");
string path = String.Concat(kioskEnginePath, ";", orgPath);
Environment.SetEnvironmentVariable("PATH", path);
}