C style string in managed class and <string.h>

G

Guest

I am trying to use a C style string in a managed class. When I try to call a function like strcmp I get an error. For example, this code

__gc MyClass
char str _nogc [16]

void foo()
strcpy(str, "Hello")



Would give the error
error C2664: 'strcpy' : cannot convert parameter 2 from 'char [16]' to 'const char *
Cannot convert a managed type to an unmanaged typ

I would use System::String, but I am porting some old code and I'd rather not rewrite every single string processing bit of it

Anyone know of a way to use C style string functions in a managed class?
 
D

Doug Harrison [MVP]

mccoyn said:
I am trying to use a C style string in a managed class. When I try to call a function like strcmp I get an error. For example, this code:

__gc MyClass {
char str _nogc [16];

void foo(){
strcpy(str, "Hello");
}
}

Would give the error:
error C2664: 'strcpy' : cannot convert parameter 2 from 'char [16]' to 'const char *'
Cannot convert a managed type to an unmanaged type


I would use System::String, but I am porting some old code and I'd rather not rewrite every single string processing bit of it.

Anyone know of a way to use C style string functions in a managed class?

The array str is physically part of a __gc object, and thus the
corresponding pointer type is an interior __gc pointer. To pass it to
strcpy, you'll have to convert it to a pinning pointer, e.g.

char __pin * p = str;
strcpy(p, "Hello");

Alternatively, you could make str a pointer and manage its memory
dynamically. Then the string data would live on the unmanaged heap, and you
could pass str to strcpy directly.
 
D

Doug Harrison [MVP]

mccoyn said:
Thanks, this seems to work well.

Is it possible to reuse a pinned variable for multiple strings, or will this create a memory leak? I want something like the following.

char __pin * ptr1;
char __pin * ptr2;

ptr1 = str1;
ptr2 = str2;
strcpy(str1, str2);

ptr1 = str3;
ptr2 = str4;
strcpy(str3, str4);

That's fine. In addition, you can unpin an object by assigning NULL to a
pinning pointer.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top