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

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

本文关键字:文件 net asp DLL 链接 应用程序 C++      更新时间:2023-10-16

我有一个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();
    }
}

似乎应该很简单。 为什么 dll 在链接到控制台应用而不是 Web 应用时有效? 我知道它执行 dll,因为它返回"失败,失败,失败......"字符串。

任何

关于该主题的文章的帮助或建议将不胜感激。 提前谢谢。

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);
}
相关文章: