8

I'm trying to write an application in Managed C++, but I cannot work out how to declare an array of strings.

String^ linet[];

throws an error

'System::String ^' : a native array cannot contain this managed type

So I suppose there's a different way to do this for managed data types. What exactly is it?

Jonathan Prior
  • 6,114
  • 7
  • 29
  • 26

3 Answers3

11

Do you really mean Managed C++? Not C++/CLI?

Assuming you're actually using C++/CLI (because of the error message you posted), there are two ways to do this:

array<String^>^ managedArray = gcnew array<String^>(10);

will create a managed array, i.e. the same type as string[] in C#.

gcroot<String^>[] unmanagedArray;

will create an unmanaged C++ array (I've never actually tried this with arrays - it works well with stl containers, so it should work here, too).

Niki
  • 15,662
  • 5
  • 48
  • 74
  • 1
    How's that work when calling String->Split() (array of strings version)? –  Nov 12 '12 at 19:34
  • @user645280 - array^ sa = str->Split(gcnew array{"one","two"}, StringSplitOptions::None); You need to specify the StringSplitOptions when using spit strings. – erict Mar 03 '18 at 18:08
4

http://www.codeproject.com/KB/mcpp/cppcliarrays.aspx

That should have all the answers you need :)

When working with Managed C++ (aka. C++/CLI aka. C++/CLR) you need to consider your variable types in everything you do. Any "managed" type (basically, everything that derives from System::Object) can only be used in a managed context. A standard C++ array basically creates a fixed-size memory-block on the heap, with sizeof(type) x NumberOfItems bytes, and then iterates through this. A managed type can not be guarenteed to stay the same place on the heap as it originally was, which is why you can't do that :)

cwap
  • 11,087
  • 8
  • 47
  • 61
  • Just a little nitpick: While Managed C++ & C++/CLI will to my knowledge be compiled into the same code, they're actually two distinct languages. – Justin Time - Reinstate Monica Jun 14 '16 at 17:37
  • From https://en.wikipedia.org/wiki/Managed_Extensions_for_C%2B%2B "...These new extensions were designated C++/CLI and included in Microsoft Visual Studio 2005.[1] The term Managed C++ and the extensions it refers to are thus deprecated and superseded by the new extensions...." - So yeah, you are absolutely correct. – cwap Jun 14 '16 at 19:08
  • I only mentioned it because Managed C++ doesn't use handles (managed pointers, declared as `type^`), but C++/CLI does. ...Now that I think about it, the person who asked the question got the two mixed up, too. – Justin Time - Reinstate Monica Jun 14 '16 at 21:38
1

You use a collection class from .Net. For example:

List<String^>^ dinosaurs = gcnew List<String^>();
1800 INFORMATION
  • 131,367
  • 29
  • 160
  • 239