Reputation: 137
I have c++ dll with class in wich I want to send string from C# code, surly I can't use string because of CLR, i'll stried to change string into char in c++ dll, and send byte from c#(because c++ char=byte in c#) but c# don't understand c++ array I can send 1 byte and it will be ok, but not array, please help! dll Code:
public ref class Coding
{
public:
void HillCoding(char filePath[])
{
...
}
};
Upvotes: 1
Views: 1665
Reputation: 1559
Here is the working code of calling C++ dll function from C#:
sbyte[] A_SB_array = new sbyte[0];
ArrayConvCtoSB(ref A_SB_array, ar_param.ToCharArray());
fixed (sbyte* SB_array = A_SB_array)
return CPSFEW.getDataLength(SB_array);
It's not the "very good code" but it illustrate what you need.
PS: Here is ArrayConvCtoSB. I do not like it, it's just for understanding.
static private void ArrayConvCtoSB(ref sbyte[] to_sbyte, char[] from_char)
{
for (int i = 0; i < from_char.Length; i++)
{
Array.Resize(ref to_sbyte, to_sbyte.Length + 1);
to_sbyte[i] = (sbyte)from_char[i];
}
}
PPS: "fixed" is strongly required for forceing garbage collector not to clear the SB_array memory: otherwise it can. :)
Upvotes: 1
Reputation: 55563
Try this first, because CLR converts string
to char *
, no?:
callThisCPlusPlusMethod(myString)
If that doesn't work, Use
char[] sendArray = myString.ToCharArray();
callThisCPlusPlusMethod(sendArray);
Or, if needed in different encoding:
byte[] sendArray = Encoding.TheEncodingINeed.GetBytes(myString);
callThisCPlusPlusMethod(sendArray);
Note: I tend to like ambiguous names :)
Upvotes: 1