# How to wrap C++ function writing to FILE\*?

**URL:** https://discourse.julialang.org/t/how-to-wrap-c-function-writing-to-file/122945
**Category:** General Usage
**Tags:** question, cxxwrap
**Created:** [November 22, 2024, 9:52am UTC](https://discourse.julialang.org/t/how-to-wrap-c-function-writing-to-file/122945 "2024-11-22T09:52:18Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![Vasily\_Pisarev](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vasily_pisarev/32/7929_2.png) [@Vasily\_Pisarev](https://discourse.julialang.org/u/Vasily_Pisarev)
#### Post date: [November 22, 2024, 9:52am UTC](https://discourse.julialang.org/t/how-to-wrap-c-function-writing-to-file/122945/1 "2024-11-22T09:52:18Z")

</div>

I want to wrap a C++ function writing to a file stream to be able to print to a file or to `stdout` (eventually I’d like to try if `redirect_stdout` would work to make it print to a custom buffer). However, CxxWrap does not want to export it saying there is no factory for the IO\_FILE type. As far as I understand, such functions are supposed to take `Ptr{Libc.FILE}` from Julia. Is it possible to do that using CxxWrap?

For the reference, the C++ library in question is Voro++. It has some output functions that use protected and private class members internally, so that I cannot just port the implementation to Julia without patching the original library.

---

<div class="post-metadata">

### Author: ![Vasily\_Pisarev](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vasily_pisarev/32/7929_2.png) [@Vasily\_Pisarev](https://discourse.julialang.org/u/Vasily_Pisarev)
#### Post date: [November 22, 2024, 9:11pm UTC](https://discourse.julialang.org/t/how-to-wrap-c-function-writing-to-file/122945/2 "2024-11-22T21:11:53Z")

</div>

Okay, I think I have found out a way to do that.

Instead of adding the needed method automatically via CxxWrap, I added a C wrapper function like the following:

```cpp
extern "C" {
    void write_data(Object* obj, FILE* fp)
    {
        obj->write_data(fp);
    }
}

```

And from Julia, I use `ccall` directly:

```julia
function write_data(io::IOStream, obj::CxxObject)
    file = Libc.FILE(io)
    ccall(
        (:write_data, "libmywrapper"),
        Cvoid,
        (Ptr{Cvoid}, Ptr{Libc.FILE}),
        obj.cpp_object, file,
    )
    close(file)
end

```
