1

I'm trying to write a wrapper for a very simple std::pair<std::string, float> in C++/CLI but I get the error message: no instance of constructor "std::pair<_Ty1, _Ty2>::pair [with _Ty1=std::string, _Ty2=float]" matches the argument list, argument types are: (std::string, float)

What am I doing wrong and why doesn't std::string match std::string?

#include <msclr\marshal_cppstd.h>
#include <string>

using namespace System;
using namespace System::Runtime::InteropServices;

typedef std::pair<std::string, float> Parameter;

static std::string StringToNative(String^ str)
{
    msclr::interop::marshal_context context;
    return context.marshal_as<std::string>(str);;
}

public ref class CLIParameter
{
public:
    CLIParameter(System::String^ name, float value) : _name(name), _value(value) {};
    Parameter toNativeParameter()
    {
        return Parameter(StringToNative(_name), _value);
    }
private:
    System::String^ _name;
    float _value;
};

int main()
{
    CLIParameter^ par = gcnew CLIParameter("test", 1);
}
cdhowie
  • 158,093
  • 24
  • 286
  • 300
MrEighteen
  • 434
  • 4
  • 16

1 Answers1

0

Your method toNativeParameter() is incorrect. It should be defined as follows:

Parameter toNativeParameter()
{
    // copy the floating point value from the managed heap to the local stack
    float value = _value; 

    // create the pair
    return std::make_pair(StringToNative(_name), value);
}

Notice that you should use std::make_pair to create the actual pair. In addition, a key step to make this work is copying the floating point value from the managed heap into the local stack. The reason is that native functions such as std::make_pair cannot create native references to an object from the managed (garbage collected) heap i.e. a member of a managed class.

Dharman
  • 30,962
  • 25
  • 85
  • 135
markf78
  • 597
  • 2
  • 7
  • 25