0

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.

1
  • Also, there is a for each syntax in C++/cli. And don't mix C++ or C calls without marshaling the data-type to the correct type. Commented Feb 13, 2014 at 0:47

3 Answers 3

2
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]);
Sign up to request clarification or add additional context in comments.

3 Comments

This code results me in string; but the value differs. what could be the reason ?
Impossible to tell from here without details
I have solved this issue, by changing the encoding, the issue was with Encoding format. :)
1

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.

1 Comment

This code is printing some values, but which is not the actual value. Does it because of any encoding issue ?
0

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] );

2 Comments

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'System::String ^' (or there is no acceptable conversion) I got for this line.. :(
@Dineshkumar Ponnusamy Try to use System::Console::WriteLine( MyString[iter] );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.