1

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[]) { ... } }; 
3
  • Can you share with us the C++ function's signature? Commented Nov 6, 2010 at 21:17
  • 1
    At runtime with P/Invoke, the CLR will convert string into char * I believe Commented Nov 6, 2010 at 21:17
  • possible duplicate of Passing NON null-terminated strings to unmanaged code Commented Nov 6, 2010 at 21:18

2 Answers 2

1

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. :)

Sign up to request clarification or add additional context in comments.

1 Comment

One more addition. Here is the declaration of getDataLength C++ function: "size_t getDataLength(const char *param) {...}"
1

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 :)

2 Comments

Error 2 Argument 1: cannot convert from 'string' to 'std.basic_string<char,std.char_traits<char>,std::allocator<char> >*'
If your signature is the same as the one above, then theoretically that should work, I have no idea what the problem would be... did you try all the other methods I posted?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.