Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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 const char *var1 and const char* var2[] as parameter.

When I call such function in C# , function accepts arguments types as sbyte*.
Just using a c#-string doesnt seem to work as the function in C# requires a sbyte* and sbyte**

C++ class:
C++
public ref class MyClass
{
public:
	void Sample(const char * var1,const char* Var2[]);
}



C# call..
C#
class Program
    {
        static void Main(string[] args)
        {
               MyClass oClass = new MyClass();
               string var1 = "Variable1";
               string[] var2 = {"1","2"};
               oClass.Sample(var1,var2);
        }
}
Error:
Error	1	Argument 1: cannot convert from 'string' to 'sbyte*'<br />
Error	2	Argument 2: cannot convert from 'string[]' to 'sbyte**'



So I need help in understanding how can I pass string arguments from managed C# to managed C++?

Thanks
Posted
Updated 15-May-13 20:46pm
v2

1 solution

The C# String are complexe objects so you need a byte array in which the chars are.

byte[] buffer = Encoding.ASCII.GetBytes(var1);

or use the Stringbuilder class

And look out for the right byte size.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900