Jörgen
Jörgen

Reputation: 316

Implementing FILE pointer in c++

I'm using a C library in my C++ project. For logging, the C library requires me to define a FILE pointer to get logs i.e.:

extern "C"
{
    FILE *pFileStdErr = stderr;
}

This will make the logs appear in the console window.

However what I really want is to capture the logs from the C library in my C++ class method, i.e.

extern "C"
{
    FILE *pFileStdErr = ???;
}

void CMyClass::Log (std::string error)
{
    m_myLogger.LogError(error);
}

So how do I "glue" this together?

Upvotes: 0

Views: 275

Answers (2)

glglgl
glglgl

Reputation: 91029

There is a non-standard extension on GNU: fopencookie(). With that, you can define the behaviour of a FILE on your own.

Even if you are not on GNU, your environment might provide something like this.

But be aware that you are losing portability if you do this.

Upvotes: 1

Radu Chivu
Radu Chivu

Reputation: 1065

You can create a pipe with the pipe function (_pipe on windows) and then use fdopen on the returned descriptors to get a FILE* pointer. Then you can set the write end of the pipe as the FILE* pointer for your library and read from the read end of the pipe in your class.

Upvotes: 0

Related Questions