如何将一个函数返回的 TCHAR* 传递给(托管)C++中的另一个函数

How to pass TCHAR* returned by one function to another function in(Managed) C++

本文关键字:函数 托管 另一个 C++ 返回 一个 TCHAR      更新时间:2023-10-16

我有一个名为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>

请参阅此问题:指向局部变量的指针