簡體   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