2
Reply

Passing string from C# to C++

Harish Iyer

Harish Iyer

Oct 27 2009 5:16 AM
4.1k

Hello,
I have a C# client in which I make a call to a C++ DLL. The C++ code looks as follows ;
BYTE mmc_write(unsigned long addr, BYTE* Buffer)
{
}
 
On the C# side, I have declared the function as
[DllImport("somecpp.dll")
internal static extern byte mmc_write(ulong addr, [MarshalAs(UnManagedType.LPStr)]string sendBuffer);
and I use it in a function as below :
int Send(string sData)
{
   byte yRet = mmc_write(0, sData);
   if(yRet > 0)
      retutn sData.Length;
   return 0;
}
 
Now when I debug, I see that the string received on the C++ side is a bad pointer. I tried wrapping the string in C# to a StringBuilder also, but to no avail.
Am I doing something wrong here ? It would be great if someone can help me in this

Answers (2)