Conversion between managed and unmanaged types in C++?

我怕爱的太早我们不能终老 提交于 2019-12-11 09:07:16

问题


When I use a GUI in C++ the text fields are stored as managed strings, i think. I need a way to convert them to standard ints, floats and strings. Any help?


回答1:


You can convert a System.String into an unmanaged char * using Marshal.StringToHGlobalAnsi. Make sure you free it when you're done by calling Marshal.FreeHGlobal. To convert the strings to numeric values, you can use the regular .NET parsing functions such as Int32.Parse.




回答2:


To use managed memory in native code, you must copy the contents of the managed memory into native memory first.

So for example:

Copying the contents from managed memory is as follows:

const int len = 50;
BYTE *destination = new BYTE[nLength];
System::Byte source[] = new System::Byte[len];

System::Runtime::InteropServices::Marshal::
  Copy(source, 0, IntPtr((void *)destination, len);

Because we are dealing with managed memory, garbage collection can shift and move the managed data to another location and all would be lost if we tried to locate the data we want to convert.

Therefore we want to "pin it in memory" by using __pin to convert from managed to unmanaged:

const int len = 50;
BYTE *source              = new BYTE[len];
System::Byte destination[]     = new System::Byte[len];
BYTE __pin *managedData = &(destination[0]);

::memcpy(source, managedData, len);



回答3:


You can simply convert System::String^ objects to MFC CString by

CString* name = new CString(managedName);

where managedName is a managed String.



来源:https://stackoverflow.com/questions/741245/conversion-between-managed-and-unmanaged-types-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!