Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How should C# handle objects allocated in Unmanaged Code?

Status
Not open for further replies.

pmccombs

Programmer
May 29, 2003
7
0
0
US
Hi,

I have written a DLL in unmanaged code that has a certain function that returns a string. This string is allocated within the function.

I can call this function from C# if I use the DllImport attribute and define a prototype in a class definition. The function works fine, and I can assign the return value of it to a C# string object.

I wonder what happens to that string object when it goes out of scope. The string was originally allocated in Unmanaged Code, from the heap. How does it get deallocated?

Thanks,

-Peter
 
This is only a guess, but I believe that the string object that you have in C# will actually be a copy of the memory that you allocated in your unmanaged code. If this is the case, the CLR (runtime) either deleted your allocated memory, or it didn't. If it didn't you probably have a memory leak. What you could try is calling that function a billion times and see if you run out of memory, or you could make a static reference to it in your function and make an additional boolean parameter that tells it to deallocate the memory. If you call your function once to get the string, then call it again to delete it, then check to see if your C# string is still intact, you will know what is happening.

So, if that blabber wasn't helpful, let me know and I will try again.

"Programming is like sex, one mistake and you have to support it forever."

John

johnmc@mvmills.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top