Search code examples
winformsc++-cli

Error when including <msclr/marshal.h> for Winforms project


Good day.

I am making a project using Winforms C++/CLI.

As of now, I am aiming to write a function that will convert the input of the user from a textbox. And from what I could gather, I am basically converting from type System::String^ to type std::string.

However, whenever I inlcude <msclr/marshal.h>, I get about 50 errors (here are the first four):

1>C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\objidl.h(12152,71): error C3699: '*': cannot use this indirection on type 'IDataObject'

1>C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\objidl.h(12152,71): message : compiler replacing '*' with '^' to continue parsing

1>C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\objidl.h(12167,5): error C2371: 'IDataObject': redefinition; different basic types

1>C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\objidl.h(590,31): message : see declaration of 'IDataObject'

I have confirmed that the error comes from me including <msclr/marshal.h>, as the mere inclusion of that header file causes the above errors to pop out.

To resolve my problem, I tried researching for ways to convert System::String^ to std::string. But, much to my dismay, almost everything revolved around using <msclr/marshal.h>. And, while there were some solutions that used <locale> and <codecvt>, all of them also resulted to a mountain of errors.

I also opened objidl.h but, I could not even begin to imagine how I could remotely understand what I need to do to fix the code; (1.) Since I did not write it, and (2) I am a noob programmer who is only at his first year of CS.

Finally, all help is appreciated. Thank you very much for your time.

convert.cpp:

#include "convert.h"
#include <string>
#include <msclr/marshal_cppstd.h>

using namespace System;

std::string sysStr_stdStr(String^ value)
{
    return msclr::interop::marshal_as<std::string>(value);
}

convert.h:

#ifndef CONVERT_H
#define CONVERT_H

#include <string>

std::string sysStr_stdStr(System::String^ value);

#endif // !CONVERT_H

Solution

  • Okay. So, I just switched from using c++20 to c++17 language standard and it resolved the issue for me. Good luck.