rpcgen-在结构中传递一个字符串

时间:2014-03-24 03:34:37

标签: c++ c unix rpc

我尝试使用rpcgen软件包在网络上传递字符串作为结构的一部分。这是我的IDL代码:

struct param
{   
    char* name;
    int voterid;
};

program VOTECLIENT_PROG
{
        version VOTECLIENT_VERS
        {
        string ZEROIZE() = 1;
                string ADDVOTER(int) = 2;
        string VOTEFOR(param) = 3;
        string LISTCANDIDATES() = 4;
        int VOTECOUNT(string) = 5;
        } = 1;
} = 0x2345111;

不知何故,字符串被截断为服务器上的单个字符。例如,如果我传递name =" abc",我会得到" a"在服务器上。由于存根中存在一些问题,看起来这种情况正在发生,但我似乎无法弄清楚错误的位置。

我将传递字符串作为参数的函数的客户端代码:

void
voteclient_prog_1(char *host, char* c, int id)
{
    CLIENT *clnt;
    char * *result_3;
    param  votefor_1_arg;

#ifndef DEBUG
    clnt = clnt_create (host, VOTECLIENT_PROG, VOTECLIENT_VERS, "udp");
    if (clnt == NULL) {
        clnt_pcreateerror (host);
        exit (1);
    }
#endif  /* DEBUG */
    votefor_1_arg.name = c;
    votefor_1_arg.voterid = id;

    result_3 = votefor_1(&votefor_1_arg, clnt);
    if (result_3 == (char **) NULL) {
        clnt_perror (clnt, "call failed");
    }
    clnt_perror (clnt, "call failed");
#ifndef DEBUG
    clnt_destroy (clnt);
#endif   /* DEBUG */
}


int
main (int argc, char *argv[])
{
    char *host;
    int id;
    char* c = new char[20];

    if (argc < 4) {
        printf ("usage: %s server_host name voterid\n", argv[0]);
        exit (1);
    }
    host = argv[1];
    c = argv[2];
    id = atoi(argv[3]);
    voteclient_prog_1 (host, c, id);
exit (0);
}

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

来自rpcgen Programming Guide,6.9。特例:

  

字符串: C没有内置字符串类型,而是使用   以null结尾的“char *”约定。在XDR语言中,字符串是   使用“string”关键字声明,并编译成“char *”   输出头文件。角度中包含的最大尺寸   括号指定允许的最大字符数   字符串(不包括NULL字符)。最大尺寸可能是   向左,表示任意长度的字符串。

     

示例:

string name<32>;   --> char *name;
string longname<>; --> char *longname;

所以,你应该如上所述声明name,e。 G。 string name<20>;

答案 1 :(得分:0)

在上面的注释中添加一些内容,rpcgen中这种数组的用法如下:

在您的结构中声明这样的数组(任何类型)

struct myStruct { //In my case I used an array of floats float nums<>; }

这将声明一个float类型的“数组”。这种结构具有两个变量成员

struct {
    u_int nums_len; 
    float *nums_val;
}nums;

现在您可以将内存分配给float类型的数组:

//totNums is the number of elements in the array
nums.nums_val = (float*)malloc(totNums*sizeof(float));
nums.nums_len = totNums;

现在在服务器中,您可以将数组与所有元素一起使用。