基於gsoap開發WebService服務返回結構體數組

基於gsoap開發WebService服務返回結構體數組


gsoap搭建和快速WebService示例編寫,前面文章已經介紹過,此文直接講關鍵點。
(1)返回的目標結構,開頭以ns__,這與第一行//gsoap ns XXX 相關,例如
struct ns__EmployeeInfo
{
    int userid;
    char* name;
};

(2)gsoap對外提供的方法中,函數返回值並不是用來返回業務數據,函數最後一個參數作爲輸出參數用來返回業務數據,那麼返回單個結構寫法:
struct ArrayOfEmp2
{struct ns__EmployeeInfo info;};
接口函數:int ns__getEmp2(void *_,struct ArrayOfEmp2 &ccc);
這個寫法你會發現,C#客戶端更新wsdl結構後的返回值是ArrayOfEmp2,其內部有一個info屬性則爲返回的結構體內容。
下面是“處女座”的寫法:
struct ns__ArrayOfEmp2
{struct ns__EmployeeInfo info;};

接口函數:int ns__getEmp2(void *_,struct ns__ArrayOfEmp2 &ccc);
好處就是,在客戶端返回值直接就是EmployeeInfo結構。

(3)重點來了,返回結構體數組的寫法:
struct ArrayOfEmp1  //此爲正確寫法
{struct ns__EmployeeInfo **__ptr;int __size;};
接口函數:int ns__getAllEmp1(void *_,struct ArrayOfEmp1 &alal);
幾個注意點:父級結構名字不要帶ns__;返回的目標結構成員的名字必須是__ptr,大小的名字必須是__size。

(4)接口實現代碼
int ns__getAllEmp1(struct soap* soap,void *_,struct ArrayOfEmp1 &_return)
{
    _return.__size = 5;
    _return.__ptr = (struct ns__EmployeeInfo**)soap_malloc(soap,5*sizeof(struct ns__EmployeeInfo));
    _return.__ptr[0] = (struct ns__EmployeeInfo*)soap_malloc(soap,sizeof(struct ns__EmployeeInfo));
    _return.__ptr[0]->userid=1000;
    _return.__ptr[0]->name= soap_strdup(soap,"name1");

    _return.__ptr[1] = (struct ns__EmployeeInfo*)soap_malloc(soap,sizeof(struct ns__EmployeeInfo));
    _return.__ptr[1]->userid=1001;
    _return.__ptr[1]->name= soap_strdup(soap,"name2");

    _return.__ptr[2] = (struct ns__EmployeeInfo*)soap_malloc(soap,sizeof(struct ns__EmployeeInfo));
    _return.__ptr[2]->userid=1002;
    //_return.__ptr[2]->name = soap_strdup(soap,"name3");
    _return.__ptr[2]->name = (char*)"name3";//這種形式的複製,也是沒關係的

    _return.__ptr[3] = (struct ns__EmployeeInfo*)soap_malloc(soap,sizeof(struct ns__EmployeeInfo));
    _return.__ptr[3]->userid = 1003;
    _return.__ptr[3]->name = (char*)"name4";

    _return.__ptr[4] = (struct ns__EmployeeInfo*)soap_malloc(soap,sizeof(struct ns__EmployeeInfo));
    _return.__ptr[4]->userid = t.id;
    _return.__ptr[4]->name = soap_strdup(soap,t.name.c_str());
    return SOAP_OK;
}

幾個作死行爲:
1、返回結構數組的父級結構體,寫法上帶ns__,如:
struct ns__ArrayOfEmp //此寫法會導致返回的結構是ArrayOfEmp,且其Item屬性爲NULL
{struct ns__EmployeeInfo **__ptr;int __size;};

2、實現接口函數中,__size字段賦值與實際數組長度不符,將導致服務器crash。


====以下無內容====




發佈了32 篇原創文章 · 獲贊 32 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章