简体   繁体   中英

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

I have a C++ dll. I would like to have it write to a log file on the server. When I link it to a console application it writes to the file just fine. When I link it to the asp.net application the file I/O fails. Not really sure what I am missing.

This is the C++ dll code that works fine when linked with console app.

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;
}

Here is the C# code behind that calls it

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

Seems like it should be pretty simple. Why does the dll work when linked to a console app but not a web app? I know it executes the dll because it returns the "fail, fail, fail.........." string.

Any help or suggestions of articles to read on the subject would be tremendously appreciated. Thanks in advance.

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

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

OR

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

OR just use the unsafe keyword:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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