问题
I'm trying to pass a string as part of a structure over the network using the rpcgen packages. This is my IDL code :
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;
Somehow, the string is being truncated to a single character at the server. For example, if I pass name = "abc", I get "a" at the server. It looks like this is happening because of some issue inside the stubs, but I can't seem to figure out where the bug is.
My client code for the function that passes the string as an argument :
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);
}
Any help will be greatly appreciated.
回答1:
From rpcgen Programming Guide, 6.9. Special Cases:
Strings: C has no built-in string type, but instead uses the null-terminated “char *” convention. In XDR language, strings are declared using the “string” keyword, and compiled into “char *”s in the output header file. The maximum size contained in the angle brackets specifies the maximum number of characters allowed in the strings (not counting the NULL character). The maximum size may be left off, indicating a string of arbitrary length.
Examples:
string name<32>; --> char *name; string longname<>; --> char *longname;
So, you should declare name
like above, e. g. string name<20>;
.
回答2:
Adding something to the comment above, the usage of this kind of array in rpcgen is like follows:
In your struct declare arrays (of any type) like this
struct myStruct {
//In my case I used an array of floats
float nums<>;
}
This declare an "array" of type float. This kind of struct has two members of variables
struct {
u_int nums_len;
float *nums_val;
}nums;
Now you can allocate memory to the array of type float:
//totNums is the number of elements in the array
nums.nums_val = (float*)malloc(totNums*sizeof(float));
nums.nums_len = totNums;
Now in the server you can use your array with all the elements.
来源:https://stackoverflow.com/questions/22600634/rpcgen-passing-a-string-inside-a-struct