0

I want to use (for example) a System.Drawing.PointF variable in C++ (/clr), using msclr::interop::marshal_as(). To do so, I add a template specialization as follows:

using namespace System::Drawing;
namespace msclr {
    namespace interop {
        template<>
        inline mynmsp::Punt marshal_as<mynmsp::Punt, PointF>(PointF const &from) {
            PointF cpf(from);
            return mynmsp::Punt(cpf.X, cpf.Y);
        }
    }
}

I was hoping to achieve this without the additional instance 'PointF cpf(from);' However, the const reference makes this impossible as far as I can see, and the PointF &from invocation won't be accepted without the const. Explicitly adding X() or X.get() does not help. I should add about myself that my C# is horrible, trying to get by with the minimum, do the real work in C++. Thanks in advance, Jan

PS: The comment by Hans Passant explains that the workaround comes at no cost in at least the Release build. I consider that a solution, because now I can add this as a comment and I will certainly keep basic jitter optimizations. Thanks.

Jan
  • 447
  • 6
  • 8
  • I'm not C++ guy, but doesn't C++/CLR mean that the compiler is going to generate managed (IL) code? Can't you use C# structs (like `PointF`) directly without interop? Note: a C# struct is a value type and I think it corresponds to value struct in C++. I found a good article in french on this subject here: [Introduction au monde du C++/CLI](https://nico-pyright.developpez.com/tutoriel/vc2005/managedworld/). – Olivier Jacot-Descombes Dec 22 '18 at 16:45
  • Grand temps pour amplifier mes pouvoirs linguistiques francaises... You are right, of course, can use the PointF etc., but need to interface with a C++ library. So the question will come back and I'm a stickler for avoiding unnecessary code/copies etc. – Jan Dec 22 '18 at 19:21
  • The PointF property accessors for the X and Y properties are not declared *const*, thus the C2662 error on the code we cannot see. It is one of the impedance mismatches between C++ and the .NETFramework, in C++ const is enforced by the compiler but the .NET designers only ever bought stock in runtime verification. Your workaround is fine, getting rid of the local variable is one of the [basic jitter optimizations](https://stackoverflow.com/a/4045073/17034). – Hans Passant Dec 22 '18 at 23:03

0 Answers0