如何将一个函数返回的 TCHAR* 传递给(托管)C++中的另一个函数
How to pass TCHAR* returned by one function to another function in(Managed) C++
我有一个名为ReversedIPAddressString的函数,它将IPAddress作为TCHAR*,然后将受人尊敬的IPAddress返回为TCHAR*。我能够很好地获得反向 IP,但是当我将此 TCHAR* 指针(反向 IP(传递给其他函数(假设 dns.query(TCHAR*((时,IP 值总是垃圾。我想知道我错过了什么?
我在这里粘贴我的代码供您参考...
调用方方法:
bool DNSService::DoesPtrRecordExixts(System::String^ ipAddress)
{
IntPtr ipAddressPtr = Marshal::StringToHGlobalAuto(ipAddress);
TCHAR* ipAddressString = (TCHAR*)ipAddressPtr.ToPointer();
bool bRecordExists = 0;
WSAInitializer initializer;
Locale locale;
// Initialize the identity object with the provided credentials
SecurityAuthIdentity identity(userString,passwordString,domainString);
// Initialize the context
DnsContext context;
// Setup the identity object
context.acquire(identity);
DnsRecordQueryT<DNS_PTR_DATA> dns(DNS_TYPE_PTR, serverString);
try
{
bRecordExists = dns.query(ReversedIPAddressString(ipAddressString)) > 0;
}
catch(SOL::Exception& ex)
{
// Free up the pointers to the resources given to this method
Marshal::FreeHGlobal(ipAddressPtr);
if(ex.getErrorCode() == DNS_ERROR_RCODE_NAME_ERROR)
return bRecordExists;
else
throw SOL::Exception(ex.getErrorMessage());
}
// Free up the pointers to the resources given to this method
Marshal::FreeHGlobal(ipAddressPtr);
return bRecordExists;
}
调用的方法:
TCHAR* DNSService::ReversedIPAddressString(TCHAR* ipAddressString)
{
TCHAR* sep = _T(".");
TCHAR ipArray[4][4];
TCHAR reversedIP[30];
int i = 0;
TCHAR* token = strtok(ipAddressString, sep);
while(token != NULL)
{
_stprintf(ipArray[i], _T("%s"), token);
token = strtok((TCHAR*)NULL, sep);
i++;
}
_stprintf(reversedIP, _T("%s.%s.%s.%s.%s"), ipArray[3], ipArray[2], ipArray[1], ipArray[0],_T("IN-ADDR.ARPA"));
return reversedIP;
}
域名系统。查询方法声明:
int query(__in const TCHAR* hostDomain, __in DWORD options=DNS_QUERY_STANDARD)
希望能得到你的帮助。
提前感谢!
拉马尼
您返回一个指向本地数组的指针,TCHAR reversedIP[30];
该数组分配给您的函数ReversedIPAddressString
。当此函数退出时,您的数组将超出范围 - 它不再存在。这是未定义的行为。
您应该返回一个字符串对象,例如std::basic_string<TCHAR>
请参阅此问题:指向局部变量的指针
相关文章:
- C++/CLI System.AccessViolation在托管类中调用非托管函数时出现异常
- c++ cuda:cudaMalloc在构造函数之外的托管访问
- C# DllImport 调用非托管C++函数回调
- 如何在 Linux 中运行 Visual Studio 2015 托管 c++ 测试函数?
- 如何在 lua cpp 模块中调用托管 c++ dll 函数
- 函数返回自定义的托管类类型
- 如何从托管C#代码拨打SystemParameterSinfow函数
- C++模板化函数调用托管函数
- 如何元使用函数返回到未托管的dll
- 导出托管的C#函数将返回更改CHAR*参数为未托管的代码
- 当未导出成员函数时,从C#调用C++本机/非托管成员函数
- 如何在托管函数中挂接非托管函数
- 通过托管C++包装程序从非托管C++dll运行C#函数
- 将托管函数指针作为非托管回调传递
- 从托管代码调用本机函数
- 这可能吗?在 C# 中调用托管 c++ 结构构造函数
- 结合函数、绑定、c++ 和托管代码
- 托管函数在非托管结构(C++、C#)中作为回调函数传递的问题
- 非托管函数中的托管类参数
- 托管类型的成员函数不能编译为非托管函数