c++serverclientrpcmidl

Remote Procedure Call and MIDL: How to implement function with [out] attribute?


I'm writing server and client using Interface Definition Language and Remote Procedure Call in C++. I can send data from client to server with [in] attribute. Now I want server to send data back to client. But I failed receiving correct data.

I define the function in .idl interface as below:

[
    //uuid and verison define here
]

interface utility{
    void sendData([in] int numIn, [out] int *numOut);
}

The MIDL document says that

An [out]-only parameter is assumed to be undefined when the remote procedure is called and memory for the object is allocated by the server.

So in client.cpp, I instantiate the variable and call the funciton.

RpcTryExcept{
    int *num;
    sendData(hBinding, 123, num);
}

In server.cpp,

void sendData(handle_t IDL_handle, int numIn, int *numOut){
    numOut = new int[3];
    numOut[0] = 1;
    numOut[1] = 2;
    numOut[2] = 3;     
}

I printed the int array in client, and get 3 random numbers. I also tried to define the size in client first. int *num = new int[3]. This time it can pass the value of numOut[0] to client, but the other indexes are all messed up. I tried char array as well but no good. Maybe I misunderstanding something. Can anyone give me some ideas? Thanks.


Solution

  • The code

    void sendData(handle_t IDL_handle, int numIn, int *numOut){
        numOut = new int[3];
        numOut[0] = 1;
        numOut[1] = 2;
        numOut[2] = 3;     
    }
    

    only changes the value copy of the pointer parameter and leaves you with a memory leak.

    I'd suspect an implementation should rather look like

    void sendData(handle_t IDL_handle, int numIn, int *numOut){
        *numOut = 42;
    }
    

    To return an array with an [out] parameter the signature would rather look like

    void sendData(handle_t IDL_handle, int numIn, int **numOut);
    

    Check your IDL definitions again.