kyamagu / mexplus

C++ Matlab MEX development kit.
Other
99 stars 49 forks source link

Add support for templated MxArray conversions #25

Open dnmiller opened 7 years ago

dnmiller commented 7 years ago

Edit: Updating with new request, as my original code was incorrect.

I'd like to first say thank you for this library. It's very useful.

I was trying to extend MxArray with conversions to/from std::array and was running into problems with deducing the type/size of the array. If I make the from function not a member of MxArray, then I can implement the conversion:

    template <typename T, size_t N>
    mxArray* from(const std::array<T, N>& value) {
        MxArray result(MxArray::Numeric<T>(N, 1));
        result.set(value);
        return result.release();
    }

If I change from to MxArray::from, then it won't compile.

A similar attempt to implement the to function does not compile in either case:

    template <typename T, size_t N>
    void MxArray::to(const mxArray* array, std::array<T, N>* value) {
        MxArray input(array);
        for (auto i = 0u; i < N; ++i) {
            (*value)[i] = input.at<T>(i);
        }
    }

This would be a great feature to have for extending to templated data types.

kyamagu commented 7 years ago

@dnmiller Hmm, you are right. Templated conversion might not work under current design. This is because there are a bunch of type inference for container template inside, and std::array will probably fall into a container kind. I don't know if documentation update is enough here.

dnmiller commented 7 years ago

Yes, that appears to be what happened. I might try and work on this if I get some spare time. Any idea what a good approach might be? Make the type inference for fromInternal more restrictive?

kyamagu commented 7 years ago

@dnmiller It would be great if you have a spare time to look into the issue. The current design defines type traits to instantiate various conversions based on type. It is probably easy to treat std::array just like std::vector. Making a template conversion on top of MxArray methods may need something more.

patrikhuber commented 6 years ago

I would also be very much interested in this! In fact I am just implementing to & from conversions for Eigen::MatrixXd. Actually, reading this issue, I am a bit surprised that so far it has worked for me, since MatrixXd is an alias to the templated class Matrix<typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>. But it's certainly possible that I'll hit a roadblock soon. Is there any update from either of you?

patrikhuber commented 6 years ago

Ah, I think I get it - in my case all template parameters are defined, so I am not hitting this problem, because I'm not templating my to/from methods. However, if I wanted to write a more generic conversion, then I'd have to "templatise" to/from and then I would hit this problem as well. So yes I would very much be interested in this! :-)