Dineshkumar
Dineshkumar

Reputation: 1548

How to call the string[] from C# to C++

I have the following function in C#.

public static string[] StringValue()
{
       .....
       return MyString;
}

I am trying to call the function in C++ using,

array<String^>^ MyString;
MyString = MyClass.StringValue();   

for(int iter=0; iter < MyString->Length; iter++)
{       
    printf("%s", MyString[iter]);       
}

The Value of MyString[iter] is not coming properly. It is proper in C# while debugging. The Length of MyString is coming proper but not the value.

Upvotes: 0

Views: 84

Answers (3)

Tom Blodget
Tom Blodget

Reputation: 20782

print is a C function and, unless really needed, is very out of place in C++/CLI code.

auto myStrings = MyClass::StringValues();
for each (auto s in myStrings) {
    Console::WriteLine(s);
}

Strings can be very difficult to work with but .NET makes it easier. If you can, keep them in .NET. Otherwise, you'll have to deal with different character sets, encodings, data structures, memory allocation and ownership transfer conventions.

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 612963

printf("%s", MyString[iter]);

This expects a pointer to null-terminated array of char. And MyString[iter] sure is not that. Since you have a managed string, in a C++/CLI assembly, you can output it like this:

Console::WriteLine(MyString[iter]);

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

Instead of

printf("%s", MyString[iter]);

try to use

for ( int i = 0; i < MyString[iter].Length; i++ )   
   std::wcout << MyString[iter][i];

EDIT: You could use

System::Console::WriteLine( MyString[iter] );

Upvotes: 0

Related Questions