0

我有一个 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,因为它返回“失败、失败、失败......”字符串。

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

4

1 回答 1

0
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();
}

或者只使用 unsafe 关键字:

//Import function just like above
unsafe
{
    char* t = Importer.LogMain();
    string s = new string(t);
}
于 2013-10-05T00:54:32.263 回答