473,836 Members | 1,586 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to convert from managed to unmanaged (and viceversa) byte arrays and strings???

Hello,

converting from the managed to the unmanaged world (and viceversa strings)
and byte arrays is something I do often and I'd like to identify the most
correct and efficient way to do it.
Also, I was wondering could there be issues in not making copies when
converting??? I was thinking, when "pointing" to the same data with both
managed and unmanaged strings/arrays couldn't there be issues such as the
garbage collector trying to reclaim memory that may not be freed (read only
memory of global unmanaged arrays and strings) or should not be yet freed
(managed strings also pointed by unmanaged string pointers)??? Should I then
always be making copies???
Bob Rock

Nov 17 '05 #1
7 7570
"Bob Rock" <no************ *************** @hotmail.com> wrote in message
news:2h******** ****@uni-berlin.de...
converting from the managed to the unmanaged world (and viceversa strings)
and byte arrays is something I do often and I'd like to identify the most
correct and efficient way to do it.
Also, I was wondering could there be issues in not making copies when
converting??? I was thinking, when "pointing" to the same data with both
managed and unmanaged strings/arrays couldn't there be issues such as the
garbage collector trying to reclaim memory that may not be freed (read only memory of global unmanaged arrays and strings) or should not be yet freed
(managed strings also pointed by unmanaged string pointers)??? Should I then always be making copies???


"Essay" questions are hard to do in a newsgroup post. :-)

That said, if you have a managed string s and you need to pass a pointer to
its constituent characters, I think that this is the way to go:

wchar_t __pin *pStr = PtrToStringChar s(s);

In case you don't know, the __pin modifier "pins" the string in memory
during the time that the pointer is in scope to keep the GC at bay.

Now bytes are the same on both sides of the .Net fence, so you won't find an
equivalent to PtrToStringChar s(). You can simply pin a pointer.

If you find yourself doing much "interop" you might want to peruse the book
"Essential Guide to Managed Extensions for C++" (ISBN: 1-893115-28-3). It's
authors, Challa and Laksberg, come from inside the big house. :-)

Regards,
Will

Nov 17 '05 #2
> "Essay" questions are hard to do in a newsgroup post. :-)

That said, if you have a managed string s and you need to pass a pointer to its constituent characters, I think that this is the way to go:

wchar_t __pin *pStr = PtrToStringChar s(s);

In case you don't know, the __pin modifier "pins" the string in memory
during the time that the pointer is in scope to keep the GC at bay.

Now bytes are the same on both sides of the .Net fence, so you won't find an equivalent to PtrToStringChar s(). You can simply pin a pointer.

If you find yourself doing much "interop" you might want to peruse the book "Essential Guide to Managed Extensions for C++" (ISBN: 1-893115-28-3). It's authors, Challa and Laksberg, come from inside the big house. :-)

Regards,
Will


Hello,

I found an article that well describes the string to char*, CString and
wchar conversion:

http://support.microsoft.com/default...b;EN-US;311259

Is char* __gc[] the same as string???

Will, if I convert a global unmanaged string to managed without making a
copy (having both point the same memory area) first or later the GC will try
to reclaim a memory resource that may not be freed .... this will probably
cause an exception. Am I mistaken??? I suppose in this case a copy must
necessarily be made.

Bob Rock


Nov 17 '05 #3
You can stop the GC from cleaning memory by using a pin pointer. As long as that variable points to the string, the GC won't move or cleanup that memory. This line

wchar_t __pin *pStr = PtrToStringChar s(s)

Creates a pinned pointer. As long as that variable doesn't change it should be safe to read the memory. You do have to watch out if the pointer is used avter the variable (pStr above) goes out of scope. For example

class U
public
wchar_t* ptr
void set_ptr(U* u)
String* str = "hello"
wchar_t __pin * pStr = PtrToStringChar s(str)

U->ptr = pStr
cout<<U->ptr<<endl; // Memory access error, the string is no longer pinned
void get_ptr(U* u)
cout<<U->ptr<<endl; // Memory access error, the string is no longer pinned
void (test)
U u
set_ptr(&u)
get_ptr(&u)
So, when assigning an unmanaged pointer as a static variable or a class member variable it is a better idea to copy it. When you are just gonig to use it within the scope of the function, you can use the pinned pointer.
Nov 17 '05 #4
"mccoyn" <an*******@disc ussions.microso ft.com> wrote in message
news:A4******** *************** ***********@mic rosoft.com...
You can stop the GC from cleaning memory by using a pin pointer. As long

as that variable points to the string, the GC won't move or cleanup that
memory.

I don't seem to be able to explain myself properly.
Ok, using a pin pointer prevents the GC from reclaiming the memory. But the
problem is, first or later the CG WILL try reclaiming it. Right???
Now, consider this situation: I have a global unmanaged unicode string such
as the following:

tchar* myString = "This is my string";

Now, global strings such as the following are keep (if I'm not mistaken) in
a read-only memory area. Now, consider what may happen if a managed string
is made to use that same exact unicode string instead of making a copy.
First or later the GC will try to reclaim that space, which is read-only and
may not be reclaimed. The consequence is obvious. Am I correct in saying
that in such situations I should always make copies when converting to a
managed string???

Bob Rock
Nov 17 '05 #5
"Bob Rock" <no************ *************** @hotmail.com> wrote in message
news:%2******** **********@TK2M SFTNGP12.phx.gb l...
Is char* __gc[] the same as string???
Well, to paraphrase a former president it depends on what you mean by
'string'. <g>

Usually when one says 'string' in a .Net context, one refers to the class
named System::String.

On the other hand, 'strings' in C are null terminated arrays of characters,
so in some sense what you describe is the managed analog of C 'strings'.
Will, if I convert a global unmanaged string to managed without making a
copy (having both point the same memory area) first or later the GC will try to reclaim a memory resource that may not be freed .... this will probably
cause an exception. Am I mistaken??? I suppose in this case a copy must
necessarily be made.


What kind of 'strings' are we talking about? Why not just create a managed
System::String from your character array and be done with it?

Regards,
Will
Nov 17 '05 #6
Thats right, but I don't think it is possible. When you assign a tchar* to a String* you end up with a function call that does the copying automatically.

tchar* myString = "This is my string";
String* str = myString;

The above code will make a copy of myString automatically. This copy will be managed by the String class and cleaned up by the GC, leaving the original myString alone. I don't know of any way to assign a __gc pointer the value from a __nogc pointer, which would lead to the problem you described. Therefore, it is always necesarry to copy the string when going from unmanaged to managed.
Nov 17 '05 #7
> > Is char* __gc[] the same as string???

Well, to paraphrase a former president it depends on what you mean by
'string'. <g>

Usually when one says 'string' in a .Net context, one refers to the class
named System::String.

On the other hand, 'strings' in C are null terminated arrays of characters, so in some sense what you describe is the managed analog of C 'strings'.

What kind of 'strings' are we talking about? Why not just create a managed
System::String from your character array and be done with it?

Regards,
Will


I've seen functions request parameters of the type char* __gc[]. I don't
know what they are ... I was asking if when I find such parameter types I
can pass in string arguments.

Bob Rock

Nov 17 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
741
by: Bob Rock | last post by:
Hello, in the last few days I've made my first few attempts at creating mixed C++ managed-unmanaged assemblies and looking aftwerwards with ILDASM at what is visible in those assemblies from a managed point-of-view I've noticed that: 1) for each managed and unmanaged C function (not C++ classes) I get a public managed static method (defined on a 'Global Functions' class) in the generated assembly with an export name of the form...
1
7236
by: Eric Hendriks | last post by:
// In an unmanaged DLL the following function must be called: // int VFGeneralize(const BYTE * const * features); // "features" parameter is supposed to be an array of byte arrays. // function is Marshaled as follows: static extern int VFGeneralize(byte features); In C# I have the following: // Allocate memory to store "Count" references to byte arrays
16
14149
by: Ekim | last post by:
hello, I'm allocating a byte-Array in C# with byte byteArray = new byte; Now I want to pass this byte-Array to a managed C++-function by reference, so that I'm able to change the content of the byteArray and afterwards see the changes in C#. (if you wanna know more details: the goal is to write the content of an existing char-array in c++ precisely into the passed byteArray, so that after the function has proceded the content of the...
6
2558
by: Omid Hodjati | last post by:
Hi All, I implemented an encryption algorithm using C#, native C++ and managed C++. Then I measured the CPU time used for executing this algorithm in all implementation. The managed version of C++ was the worst ! It is 20 times slower that the native version and 6 times slower that the C# versio !! Because i wanted to use automatic memory management offered by .Net framework, i used the managaed classes available. e.g. i have used...
2
5274
by: Herbert VON GRÜNENWALD | last post by:
i'v got: public static extern int ReadFile( IntPtr hFile, IntPtr lpBuffer, uint nNumberOfBytesToRead, ref uint lpNumberOfBytesRead, uint lpOverlapped);
7
8234
by: Klaus Bonadt | last post by:
I have an existing VC6 application using the MFC. I am able to pass CString and other parameters from such a VC6 dll to an unmanaged MFC dll (compiled in Visual Studio .NET). Now I want to use .Net functionality, i.e. calling methods in managed code. How do I pass CString variables for input and output usage, i.e. providing and retrieving char arrays? Regards, Klaus
2
2346
by: Howard Weiss | last post by:
I am reading a file (containing short integers). To read the file, I use the following FileStream *myFile = new FileStream(FileName, FileMode::Open, FileAccess::Read); __int64 myFileSize = myFile->get_Length(); Byte myFileData; myFile1Data = new Byte;
8
5917
by: Serge BRIC | last post by:
My application, written in .NET VB, tries to get a communication port handle from a TAPI object with this code: Dim vFileHandle As Byte() = appel.GetIDAsVariant("comm/datamodem") The vFileHandle is supposed to be a file handle (an IntPtr, I suppose). How can I convert this Byte() in this IntPtr ?
6
5901
by: Aston Martin | last post by:
Hi All, ********************** My Situation ********************** I am working on project that involves passing a structure to unmanaged code from .Net world (well using C#). Perhaps an example will prove useful. structure MyStruct { // this is a complicated struct declaration in the sense
0
9825
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9673
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10859
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10602
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10260
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7795
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6984
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5829
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4463
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.