Results 1 to 2 of 2

Thread: [RESOLVED] Call managed function from unmanaged function?

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Sep 2005
    Posts
    1,547

    Resolved [RESOLVED] Call managed function from unmanaged function?

    I am trying

    Code:
    #pragma managed
    
    String * GetWebsiteData(char * url)
    {
    	HttpWebRequest * req = (HttpWebRequest*)HttpWebRequest::Create(url);
    	HttpWebResponse * resp = (HttpWebResponse*)req->GetResponse();
    	StreamReader * sr = new StreamReader(resp->GetResponseStream());
    	String * ret = sr->ReadToEnd();
    	return ret;
    }
    
    #pragma unmanaged
    void UnmanagedFunc()
    {
    	std::string str = GetWebsiteData("A");
    }
    How do you pass/return a string?

  2. #2

    Thread Starter
    Frenzied Member
    Join Date
    Sep 2005
    Posts
    1,547

    Re: Call managed function from unmanaged function?

    Okay I resolved this, found tons of examples of passing/returning ints but not much on strings. (strings are the only problem class)

    Code:
    std::string MStr2UStr(String ^ str)
    {
    	IntPtr ptr = Marshal::StringToHGlobalAnsi(str);
    	if (ptr != IntPtr::Zero)
    	{
    		std::string ret(reinterpret_cast<char*>(static_cast<void*>(ptr)));
    		Marshal::FreeHGlobal(ptr);
    		return ret;
    	}
    	return std::string();
    }
    std::string GetWebsiteData(std::string Surl)
    {
    	try
    	{
    		String ^ url = gcnew String(Surl.c_str());
    		HttpWebRequest ^ req = (HttpWebRequest^)HttpWebRequest::Create(url);
    		HttpWebResponse ^ resp = (HttpWebResponse^)req->GetResponse();
    		StreamReader ^ sr = gcnew StreamReader(resp->GetResponseStream());
    		String ^ ret = sr->ReadToEnd();
    		return MStr2UStr(ret);
    	}
    	catch (Exception ^ ex)
    	{
    		return std::string();
    	}
    }
    Usage:
    Code:
    std::string Site = "http://mysite.com";
    std::string str = GetWebsiteData(Site);
    and the article that helped me.
    http://www.codeproject.com/KB/string...Convertor.aspx

    I was a bit confused at first, but managed/unmanaged is cool. I can now use low level hooks with high level libraries.

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