在這一課,您將使用 MyPublisher::publishMyDataWriter 向 MyTopic 發佈資料。 若要發佈資料,您必須起始設定 MyTopicStruct 的實例並完成其屬性。與 struct 起始設定相關的程式碼以及向其新增值的程式碼不是標準的 DDS API 程式碼。 它特定於您所使用的 DDS 實作 - RTI 還是 OpenSplice。 您的程式碼基於從 DDSMyTopicStructLib.idl 檔案產生的程式碼。
若要新增程式碼以向您的主題發佈資料:
char buff[32]; for (int i = 1; i <= 10; ++i) { OMDelay(1000); MyTopicStruct myTopicStruct; #ifndef USE_OSPL_IMPLEMENTATION MyTopicStruct_initialize(&myTopicStruct;); #endif myTopicStruct.myKeyAttribute = i; myTopicStruct.myLongAttribute = i; myTopicStruct.myBooleanAttribute = (i % 2); myTopicStruct.myDoubleAttribute = 1./i; //起始設定 myStringAttribute sprintf(buff, "message number %d", i); #ifdef USE_OSPL_IMPLEMENTATION myTopicStruct.myStringAttribute = DDS::string_dup(buff); #else //RTI unsigned int buffLength = strlen(buff); if (!RTICdrType_copyString(myTopicStruct.myStringAttribute, buff, buffLength + 1)) { return; } #endif //起始設定 myLongSequence #ifdef USE_OSPL_IMPLEMENTATION myTopicStruct.myLongSequenceAttribute.length(3); myTopicStruct.myLongSequenceAttribute[0] = i; myTopicStruct.myLongSequenceAttribute[1] = i+1; myTopicStruct.myLongSequenceAttribute[2] = i+2; #else //RTI const signed int ar[3] = {i, i+1, i+2}; if (!myTopicStruct.myLongSequenceAttribute.from_array(ar, 3)) { return; } #endif //發佈 myTopicStruct publishMyDataWriter(myTopicStruct); #ifndef USE_OSPL_IMPLEMENTATION MyTopicStruct_finalize(&myTopicStruct;); #endif }
若要瞭解如何用資料對 MyTopicStruct 進行起始設定,請在位於 MyTopicStructLib 網域參與者資料夾的 DefaultConfig 資料夾中(例如,<Rational® Rhapsody® 安裝資料夾>\DDSProject3\MyTopicStructLib\DefaultConfig),透過任意文字編輯器開啟 DDSMyTopicStructLib.cxx 及 DDSMyTopicStructLib.h 檔案。這些檔案是在建置 MyTopicStructLib 過程中從 DDSMyTopicStructLib.idl 檔案產生的。透過檢查 DDSMyTopicStructLib.h 檔案,尋找我們在範例程式碼中用於起始設定及終結 MyTopicStruct 實例的 MyTopicStruct_initialize 及 MyTopicStruct_finalize 函式。from_array 函式可透過對 DDS_LongSeq 定義執行部分研究後發現的陣列對 myLongSequenceAttribute 進行起始設定,其類型為 myLongSequenceAttribute,並位於 DDSMyTopicStructLib.h 檔案中。如果您使用 RTI DDS 實作,則透過檢查 DDSMyTopicStructLib.cxx 檔案中的 MyTopicStruct_copy 函式,尋找我們在範例程式碼中用於起始設定 myStringAttribute 屬性的 RTICdrType_copyString 函式的呼叫。
p_MyPublisher->publishData();