clamp
clamp

Reputation: 34036

pass a string from managed C# to managed C++

what is the preferred method to pass a string between C++ and C#?

i have a c++ class where one of the functions takes a char const * const as parameter.

how would i call this function in C#? just using a c#-string doesnt seem to work as the function in C# requires a sbyte*

C++ class:

public ref class MyClass
{
public:
    void Sample(char const * const Name);
}

Error 2 Argument '1': cannot convert from 'string' to 'sbyte*'

thanks!

Upvotes: 3

Views: 2805

Answers (3)

helium
helium

Reputation: 1078

IMO the best way would be to write a wrapper in C++/CLI that uses Marshal::StringToHGlobalAnsi or something like that to convert the System::String^ to a char pointer and than call that wrapper from C#.

Upvotes: 1

Smallgods
Smallgods

Reputation: 237

You need to try casting your parameter in C# as an sbyte.

Sample((sbyte)nameOfParameter);

That should then work fine.

Upvotes: 1

denisenkom
denisenkom

Reputation: 414

If you are using managed C++, you can use System.String class

Upvotes: 4

Related Questions