CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7

Threaded View

  1. #6
    Join Date
    Jul 2010
    Posts
    18

    Re: gcnew, interop, and OutOfMemoryException

    I think I am getting the hang of memory in c++/cli. So this native function:

    Code:
    int WriteToBuffer(HDIB hdib, int nFormat, BYTE* pBuffer, int nbMax);
    can be wrapped like this:

    Code:
    int Toolkit::Dib::WriteToBuffer(System::IntPtr hdib, int nFormat, array<Byte>^&#37; pBuffer, int nbMax)
    {
    	pin_ptr<Byte> p = &pBuffer[0];
    	return ::WriteToBuffer((HDIB)hdib.ToPointer(), nFormat, (BYTE*)p, nbMax);
    }
    and memcpy can be used to convert a String^ to a char* like this:

    Code:
    const char * SystemStringToCSTR(System::String^ sz)
    {
    	char ret [255];
    	IntPtr hglobal;
    	
    	hglobal = Marshal::StringToHGlobalAnsi(sz);
    	memcpy_s(ret, 255, (char*)hglobal.ToPointer(), strlen((char*)hglobal.ToPointer()));
    	Marshal::FreeHGlobal(hglobal);
    
    	return ret;
    }
    (*Note*)
    the above function does not work, because ret is an adress of memory that does not last beyond this function. To surcumvent this for the time being I made "char ret" into "static char ret", however this has an issue. If you were to call this function twice in the same callee, it will overright itself:

    Code:
    char * one = SystemStringToCSTR(first);
    char * two = SystemStringToCSTR(last);
    one now is overwritten. For my case it (sort of) works because I am only calling it once per function so far. however, this is not very scalable.
    Last edited by TFobear; August 6th, 2010 at 08:50 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured