1

I have a function in C++ that writes text into an std::ostream

void foo_cpp(std::ostream* log)
{
    (*log) << "foo" << std::endl;
}

The C++ code is called from C# code using a managed layer with CLI. Currently the managed C layer gets a path to a file, creates an ofstream object and passes this to the C++ code:

void foo_cli(String^ filePath)
{
    msclr::interop::marshal_context context;
    const std::string logPathCpp = msclr::interop::marshal_as<std::string>(filePath)
    std::ostream* log = new ofstream(logPathCpp);
    foo_cpp(log);
}

How can I move the logic of creating the output stream to the C# code. Something like:

void foo_csharp()
{
    FileStream log = new FileStream(@"D:\log.txt", FileMode.Create, FileAccess.Write);
    foo_cli2(log);
}

void foo_cli2(FileStream^ logCsharp)
{
    std::ostream* logCpp = someMagic<std::ostream*>(logCsharp);
    foo_cpp(logCpp);
}
SIMEL
  • 8,745
  • 28
  • 84
  • 130
  • 1
    That doesn't look like **C++**. It looks like Microsoft's **C++/CLI**. You should remove the `c++` tag, and add the `c++-cli` tag. – Eljay Jul 27 '23 at 23:48
  • `String^` -- `FileStream^` -- There is no such thing as using the `^` operator this way in C++. Better you use the right tags and remove `C++`. – PaulMcKenzie Jul 27 '23 at 23:52
  • @Eljay I didn't see that tag before, thank you. – SIMEL Jul 27 '23 at 23:57
  • I recommend passing `std::ostream` by reference instead of pointer. – Thomas Matthews Jul 27 '23 at 23:58
  • @PaulMcKenzie only `foo_cpp` is `c++` code, the other are `CLI`, I chaged the names to better reflect this. – SIMEL Jul 27 '23 at 23:58
  • @ThomasMatthews the `c++` code can't be changed. – SIMEL Jul 27 '23 at 23:59
  • You can try doing what is described in [this answer](https://stackoverflow.com/a/476014/71141), using `logCsharp->SafeFileHandle->DangerousGetHandle().ToPointer()` instead of calling `CreateFile` to get `file_handle`. – Etienne de Martel Jul 28 '23 at 01:31

0 Answers0