繁体   English   中英

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

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

我有一个名为ReversedIPAddressString的函数,该函数将IPAddress作为TCHAR *,然后将经过验证的IPAddress返回为TCHAR *。 我能够获得反向​​IP罚款,但是当我将此TCHAR *指针(reversedIP)传递给其他一些功能(例如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;
}

DNS.Query方法声明:

int query(__in const TCHAR* hostDomain, __in DWORD options=DNS_QUERY_STANDARD)

希望得到您的帮助。

提前致谢!

拉玛尼

您将返回一个指向本地数组TCHAR reversedIP[30];的指针TCHAR reversedIP[30]; 它与您的函数ReversedIPAddressString分配。 当该函数退出时,您的数组将超出范围-它不再存在。 这是未定义的行为。

您应该返回一个字符串对象,例如std::basic_string<TCHAR>

看到这个问题: 指针到本地变量

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM