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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

releasing of pointer memory in unmanaged code

Status
Not open for further replies.

nastoski

Technical User
Oct 21, 2003
21
0
0
Dear All,
i'm facing a problem with releasing of pointer mamory. Let me explain.

From a .NET environment I need to call custom API functions in a WIN32 dll written in C/C++. In order to do this I am writing a managed wrapper class using managed extensions for C++. I use the IJW approach by explicit marshalling. One of the API functions in the dll expects a char** pointer as argument and should return some data on that pointer. Here is sample code from my managed wrapper class:



IntPtr ptrToString = Marshal::StringToHGlobalAnsi(myStringBuilder ->ToString());

char *temp = (char*) ptrToString.ToPointer();

char **response = &temp;



int result = APIfunction(response);



IntPtr ptrToResponse = *response;

String *myData = Marshal::ptrToStringAnsi(ptrToResponse);



The data is transferred fine, however when I try to release the pointer memory I get:

if I try:

Marshal::FreeHGlobal(ptrToString); //ok



If I try:

Marshal::FreeHGlobal(ptrToResponse); //error:”The handle is invalid.”



If I try:

free(*response);

the freeing fails on _CrtIsValidHeapPointer(const void * pUserData);



The code in the API function from the dll uses

*response = (char*) malloc (size);

and then assigns some data to the pointer and after that the function returns.



It seems to me that the API in the dll allocates memory from it’s own Run-Time C local heap and assigns that address to *response

When I try to release the memory in my code it fails since the pointer points to a different local heap.



How to resolve the release of the pointer memory?

Please help,

Regards,
Igor
 
The API must have a method that deletes the memory itself. See if it has a function that you can pass the pointer to and have it free it.
If you try to delete memory across a DLL boundary you'll blow up.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top