繁体   English   中英

链接到asp.net c#应用程序时C ++ dll无法写入文件

[英]C++ dll fails to write to file when linked to asp.net c# application

我有一个C ++ dll。 我想将其写入服务器上的日志文件。 当我将其链接到控制台应用程序时,它会写入文件。 当我将其链接到asp.net应用程序时,文件I / O失败。 不太确定我缺少什么。

与控制台应用程序链接时,这是可以正常工作的C ++ dll代码。

char* LogHelper()
{
  char* buff = new char[500];

  std::ofstream myfile;
  myfile.open("testlog.txt",ios::out);
  if(myfile.is_open())
    strcpy(buff,"we made it");
  else
    strcpy(buff,"fail, fail, fail..........");


  return buff;
}

这是调用它的C#代码

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [DllImport("C:\\Dev\\ChatLib\\Debug\\ChatLib.dll")]
    public static extern string dllStartMain();

    protected void b1_Click(object sender, EventArgs e)
    {
      t1.Text = dllStartMain();
    }
}

似乎应该很简单。 链接到控制台应用程序但不链接到Web应用程序时,为什么dll起作用? 我知道它执行dll是因为它返回了“ fail,fail,fail ..........”字符串。

任何有关该主题的文章的帮助或建议,将不胜感激。 提前致谢。

extern "C" __declspec char* LogMain();
{
    //Put your code here..
    //return the char*.
}

[DllImport("ChatLib.dll", CallingConvention = CallingConvention.Cdecl)]
static extern StringBuilder LogMain();

要么

public static class Importer
{

    [DllImport("ChatLib.dll", EntryPoint = "LogMain", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
    [return: MarshalAs(UnmanagedType.LPStr)]
    public static extern string LogMain();
}

public static void main(String args[])
{
    string s = Importer.LogMain();
}

或者只使用不安全的关键字:

//Import function just like above
unsafe
{
    char* t = Importer.LogMain();
    string s = new string(t);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM