(Day 2 of learning c#) I am passing a buffer to a C dll from C#. The C func copies the string “text” into the buffer. Back in the C# code, I compare “text” with what’s in the buffer and it doesn’t compare equal. What am I missing?
extern "C" __declspec( dllexport )
int cFunction(char *plotInfo, int bufferSize)
{
strcpy(plotInfo, "text");
return(0);
}
c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
[DllImport("mcDll.dll", CallingConvention = CallingConvention.Cdecl,
CharSet=CharSet.Ansi)]
public static extern int cFunction(StringBuilder theString, int bufSize);
static void Main(string[] args)
{
StringBuilder s = new StringBuilder(55);
int result = cFunction(s, 55);
Console.WriteLine(s);
string zz = "text";
if (s.Equals(zz))
Console.WriteLine( "strings compare equal");
else
Console.WriteLine("not equal");
Console.ReadLine();
}
}
}
sis aStringBuilder, whilezzis astring.Try comparing
Generally,
Equals()performs a reference comparison for reference types. Some classes (such as String) overrideEquals()to allow for strings that contain the same characters to be considered equal (though for performance purposes, I believe the actual implementation first checks for reference equality, then compares the contents of each string).Your current code is calling the .Equals() method of
StringBuilder.