[Mono-dev] String comparison failing between C# and C

Robert Jordan robertj at gmx.net
Thu Nov 15 17:14:17 EST 2007


Hi Dan,

please reply to the list.

After invoking getString() the first time, mono will free the
unmanaged string, which will corrupt your global _cp field.

Change you code to always return new instances of the string,
allocated from the heap either using malloc or functions using
malloc, e.g. strdup.

Robert

Dan Osawa wrote:
> Sorry, I should have included the C code.  I am actually allocating memory
> from the heap.
> 
> char * _cp=0;
> 
> void setString(char * cp)
> 
> {
> 
> if(_cp != 0)
> 
> delete[] _cp;
> 
> _cp = new char[strlen(cp)+1];
> 
> strcpy(_cp, cp);
> 
> }
> 
> char * getString()
> 
> {
> 
> return _cp;
> 
> }
> 
> 
> 
> 
> 
> On 11/15/07, Robert Jordan <robertj at gmx.net> wrote:
>> Dan Osawa wrote:
>>> Hello,
>>>
>>> I'm currently testing Mono's interoperability between C# and C code, and
>>> have run into an interesting scenario.
>>>
>>>
>>>
>>> In my test case I have a C shared object that implements two functions:
>>> setString and getString.  The first function, setString, simply copies
>> the
>>> string into a local buffer.  The second function, getString, returns a
>>> pointer to the internal buffer holding the string.
>>>
>>>
>>>
>>> What's interesting is that the first case (in the below C# code) fails
>> when
>>> it tries to compare "hello" against the return value of getString.  Is
>> this
>>> a problem with trying to compare a unicode string with an ansi
>> string?  This
>>> test case passes when running under Windows via CLR...fails in Linux via
>>> Mono.
>> The error is most likely in your C code you didn't post.
>> You're probably returning a const ptr to a string:
>>
>> char *
>> getString ()
>> {
>>        return "hello";
>> }
>>
>> This is wrong. The interop rules demand that that string was
>> allocated from the heap:
>>
>> char *
>> getString ()
>> {
>>        return strdup ("hello");
>> }
>>
>>
>> Robert
>>
>> _______________________________________________
>> Mono-devel-list mailing list
>> Mono-devel-list at lists.ximian.com
>> http://lists.ximian.com/mailman/listinfo/mono-devel-list
>>
> 




More information about the Mono-devel-list mailing list