[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?
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.