locked
vc++ 2008 define global object - how ? RRS feed

  • Question

  • using namespace System;
    using namespace System::Net;
    using namespace System::Net::Sockets;
    void UDPinit(void){
         Socket ^udpSvr=gcnew Socket(
           AddressFamily::InterNetwork,SocketType::Dgram,ProtocolType::Udp);
          IPEndPoint ^localIp=gcnew IPEndPoint(IPAddress::Parse("127.0.0.1"),8000);
          udpSvr->Bind(localIp);
    }

    hello forum

    I want define the above UDP object globally

    and then call udpSvr->Send( ... ) from another point inside my code

    how can I do this ?

    thank you

    Wednesday, April 2, 2014 3:55 PM

Answers

  • That's C++/CLI, you can't have global variables in C++/CLI. What you can do is to create a class and make udpSvr a static member of that class:

    ref struct Global {
        static Socket ^udpSvr;
    };
    
    void UDPinit() {
        Global::udpSvr = gcnew Socket(AddressFamily::InterNetwork, SocketType::Dgram, ProtocolType::Udp);
        IPEndPoint ^localIp = gcnew IPEndPoint(IPAddress::Parse("127.0.0.1"), 8000);
        Global::udpSvr->Bind(localIp);
    }
    
    Wednesday, April 2, 2014 4:01 PM

All replies

  • That's C++/CLI, you can't have global variables in C++/CLI. What you can do is to create a class and make udpSvr a static member of that class:

    ref struct Global {
        static Socket ^udpSvr;
    };
    
    void UDPinit() {
        Global::udpSvr = gcnew Socket(AddressFamily::InterNetwork, SocketType::Dgram, ProtocolType::Udp);
        IPEndPoint ^localIp = gcnew IPEndPoint(IPAddress::Parse("127.0.0.1"), 8000);
        Global::udpSvr->Bind(localIp);
    }
    
    Wednesday, April 2, 2014 4:01 PM
  • read up on the singleton pattern.

    Then take very great care to consider how you will release the resource when you are finished with it.

    Friday, April 4, 2014 12:44 PM