Getting unmanaged text out of .NET

  • Thread starter Thread starter Mike Windsor
  • Start date Start date
M

Mike Windsor

I'm hoping this is quite a simple query, but I've spent some time reading
the documentation and I can't seem to get anywhere.

I have a .NET front-end (C++) which has to talk to unmanaged code doing the
actual work behind the scenes. I need to pass a string (representing a
filename) to the unmanaged code so it can create an output file for some
data using an ofstream object.

All the Strings / char arrays that I seem to be able to make are __gc, which
cannot be passed to unmanaged code.

How do I (hopefully without too much mess) get an un-managed string or
char[] out of the .NET framework?

Thanks for your help!

Mike
 
Mike,

In the .NET Framework there is a class called Marshal. Among the many
methods there are some that should ease your interaction with unmanaged
code.

See the documentation for more details.

Gabriele
 
If your unmanaged code takes unicode strings and your .NET code is managed
C++ you can use PtrToStringChars to get an interior pointer to the internal
array of characters in a managed string. You can then pin the pointer and
pass the pointer to the unmanaged code:

// #include vcclr.h

String* str = "hello";
const Char __pin* p = PtrToStringChars(str);
_putws(str);

The string has to be pinned because it is a pointer into a managed object,
so using __pin tells the GC to 'pin' the entire object (str) so that it is
not moved in memory while the unmanaged code is called.

Richard
--
my email (e-mail address removed) is encrypted with ROT13 (www.rot13.org)

Mike said:
That's great - thanks very much for your help. It looks like this
class is exactly what I was looking for.

I can't get the thing to actually work... but at least it looks like
it should.

Thanks again.
Mike


Gabriele G. Ponti said:
Mike,

In the .NET Framework there is a class called Marshal. Among the many
methods there are some that should ease your interaction with
unmanaged code.

See the documentation for more details.

Gabriele

Mike Windsor said:
I'm hoping this is quite a simple query, but I've spent some time
reading the documentation and I can't seem to get anywhere.

I have a .NET front-end (C++) which has to talk to unmanaged code
doing the actual work behind the scenes. I need to pass a string
(representing a filename) to the unmanaged code so it can create an
output file for some data using an ofstream object.

All the Strings / char arrays that I seem to be able to make are
__gc, which cannot be passed to unmanaged code.

How do I (hopefully without too much mess) get an un-managed string
or char[] out of the .NET framework?

Thanks for your help!

Mike
 
Back
Top