从远程过程调用返回字符串

问题描述 投票:1回答:2

我正在使用Linux中的rpcgen,我需要在C中构建一个程序来读取远程计算机上的文件,然后将该文本发送回客户端计算机以便显示。

是否可以在my-prog.x中定义一个函数,该函数向客户端返回可变长度的字符数组?

c file rpc
2个回答
0
投票

在C中,string实际上是char*

char**可以是一个字符串数组。


0
投票

有几个选项可以从C函数返回一个字符串,包括以下内容:

  1. int function(char * string,size_t length);
  2. This version allows the caller to supply their own string buffer where the RPC string will be copied. However, this version is somewhat awkward when the actual size of the string is not known to the caller; causing them to forever guess that the buffer they supply is long enough. The return 'int' value of this function might return a numeric error code to the caller, to indicate that the buffer is too small, etc.
  3. int function(char ** string);
  4. This version allows the function to allocate memory of suitable size for the string, and then return the address of that memory to the caller. Of course, this will require the caller to 'free()' the memory when it is no longer needed. The return 'int' value of this function might return a numeric error code to the caller, to indicate that it could not successfully allocate memory, etc. caller
  5. char * function();
  6. This version allows the function to allocate memory, just as in [2.] above. The difference being that it doesn't return the address of the allocated memory through a parameter. Rather, it returns the address as the value of the function. Error reporting is limited with this version in that it would probably return 'NULL' to indicate an error; which is awkward if there a number of error conditions that might occur, and need to be reported to the caller.

根据您的需要,可以使用其中任何一种。

© www.soinside.com 2019 - 2024. All rights reserved.