PowerBuilderNativeInterfaceProgrammersGuideandReference
AudienceThisbookisforC++programmerswhowillusethePowerBuilderNativeInterface(PBNI)tobuildPowerBuilder®extensions.ThebookassumesthatyouarefamilarwiththeC++languageandaC++developmenttool.
RelateddocumentsThisbookcontainsinformationaboutbuildingPowerBuilderextensions.ThePowerBuilderExtensionReferencecontainsinformationaboutusingextensionsthatareprovidedwithPowerBuilder.
OthersourcesofinformationUsetheSybase®GettingStartedCD,theSyBooks™CD,andtheSybaseProductManualsWebsitetolearnmoreaboutyourproduct:
TheGettingStartedCDcontainsreleasebulletinsandinstallationguidesinPDFformat,andmayalsocontainotherdocumentsorupdatedinformationnotincludedontheSyBooksCD.Itisincludedwithyoursoftware.ToreadorprintdocumentsontheGettingStartedCD,youneedAdobeAcrobatReader,whichyoucandownloadatnochargefromtheAdobeWebsiteusingalinkprovidedontheCD.TheSyBooksCDcontainsproductmanualsandisincludedwithyoursoftware.TheEclipse-basedSyBooksbrowserallowsyoutoaccessthemanualsinaneasy-to-use,HTML-basedformat.SomedocumentationmaybeprovidedinPDFformat,whichyoucanaccessthroughthePDFdirectoryontheSyBooksCD.ToreadorprintthePDFfiles,youneedAdobeAcrobatReader.RefertotheSyBooksInstallationGuideontheGettingStartedCD,ortheREADME.txtfileontheSyBooksCDforinstructionsoninstallingandstartingSyBooks.TheSybaseProductManualsWebsiteisanonlineversionoftheSyBooks™CDthatyoucanaccessusingastandardWebbrowser.Inadditiontoproductmanuals,youwillfindlinksto
EBFs/Maintenance,TechnicalDocuments,CaseManagement,SolvedCases,newsgroups,andtheSybaseDeveloperNetwork.ToaccesstheSybaseProductManualsWebsite,gotoProductManuals.
ConventionsTheformattingconventionsusedinthismanualare:
Formattingexample Toindicate
RetrieveandUpdate
Whenusedindescriptivetext,thisfontindicates:Command,function,andmethodnamesKeywordssuchastrue,false,andnullDatatypessuchasintegerandcharDatabasecolumnnamessuchasemp_idandf_nameUser-definedobjectssuchasdw_emporw_main
variableorfilename
Whenusedindescriptivetextandsyntaxdescriptions,obliquefontindicates:
Variables,suchasmyCounterPartsofinputtextthatmustbesubstituted,suchaspblname.pbdFileandpathnames
File>Save
Menunamesandmenuitemsaredisplayedinplaintext.Thegreaterthansymbol(>)showsyouhowtonavigatemenuselections.Forexample,File>Saveindicates"selectSavefromtheFilemenu."
dw_1.Update()
Monospacefontindicates:InformationthatyouenterinadialogboxoronacommandlineSamplescriptfragments
Sampleoutputfragments
IfyouneedhelpEachSybaseinstallationthathaspurchasedasupportcontracthasoneormoredesignatedpeoplewhoareauthorizedtocontactSybaseTechnicalSupport.Ifyoucannotresolveaproblemusingthemanualsoronlinehelp,pleasehavethedesignatedpersoncontactSybaseTechnicalSupportortheSybasesubsidiaryinyourarea.
ProgrammersGuideThispartprovidesanintroductiontothePowerBuilderNativeInterfaceandaguidetocreatingPowerBuilderextensionsandinteractingwithPowerBuilder.
IntroductiontoPBNI
AboutthischapterThischapterprovidesabriefintroductiontothePowerBuilderNativeInterface.
ContentsTopic
AboutPBNI
TheelementsofPBNI
ThePBNISDK
ComparingPBNIandJNI
AboutPBNIPBNIisastandardprogramminginterfacethatenablesdeveloperstoextendthefunctionalityofPowerBuilder.UsingPBNI,youcancreateextensionstoPowerBuilder—nonvisual,visual,andmarshalerextensions—andembedthePowerBuildervirtualmachine(PBVM)intoC++applications.ThroughtheJavaNativeInterface(JNI)andPBNI,JavaapplicationscanalsocommunicatewiththePBVM.Usewith.NETtargets
Youcanusethebuilt-inWebservicesclientextension(pbwsclient125.pbx)inapplicationsthatyouplantodeployto.NETasaPowerBuilder.NETWindowsFormsapplication.YoucannotuseanyotherPBNIextensionsina.NETtarget.Codesamples
ThisdocumentationcontainstwocompletebutverysimpleexamplesthatillustratesomebasicprinciplesofusingthePowerBuilderNativeInterface(PBNI):"Nonvisualextensionexample"and"CreatingaPowerBuilderobjecttobecalledfromC++".Formorereal-worldexamples,seethePBNIsectionofthePowerBuilderCodeXchangeWebsite.Thefollowingdiagramillustratesthetwo–waycommunication,withbothPowerBuilderextensionsandexternalapplications,thatPBNIprovidesforthePBVM.Asthediagramshows,aPowerBuilderextensioncommunicateswiththePBVMthroughtheIPB_Sessioninterface,andthePBVMcommunicateswiththeextensionthroughaninterfacederivedfromIPBX_UserObject.C++andJavaextensionscommunicatewiththePBVMthroughtheIPB_VMandIPB_Sessioninterfaces.Figure1-1:InteractionbetweenthePBVMandexternalapplicationsandextensions
UnderstandingPowerBuilderextensionsAPowerBuilderextensionisjustwhatitsnamesuggests:anextensiontoPowerBuilderfunctionalityprovidedbyyou,byathirdparty,orbySybase.AllPowerBuilderextensionscommunicatewiththePBVMthroughaninterfacecalledIPB_Session.ThisinterfaceandotherPBNIobjectsandinterfacesaredescribedin"TheelementsofPBNI".PowerBuilderprovidesitsownextensions,includingaPBDOMXMLparserandclassesthatsupportSOAPclientsforWebservices.Infuturereleases,SybasemightdevelopmorenewfeaturesasPBNIextensionsinsteadofembeddingtheminthePowerBuilderVM(PBVM),sothatthesizeofthePBVMcanbeminimized.Extensionsarealsoavailablefromthirdpartycontributors;forthelatestsamplesandutilities,seethePBNIsectionofthePowerBuilderCodeXchangeWebsite.
NonvisualextensionsThemostfrequentlyusedtypeofPowerBuilderextensionisanonvisualextension.NonvisualextensionsprovideawaytocallCandC++functionsfromPowerBuilderwithmoreflexibilitythantheprevioussolutionofdeclaringafunctioninascript.Theyalsoallowyoutouseobject-orientedtechniqueswhenworkingwithexternalobjects.AnonvisualextensionisaDLL,writteninC++,thatexposesoneormorenativeclassesand/orglobalfunctions.ClassesareusedinaPowerBuilderapplicationasthoughtheywereclassuserobjectscreatedinPowerBuilder—anativeclassissimplyaPowerScriptclassthatisimplementedinC++.GlobalfunctionsinanextensionareusedlikeglobalfunctionsdeclaredintheFunctionpainter.NonvisualextensionsallowyoutousedatatypesinC++thatmaptostandardPowerBuilderdatatypes.PBNIprovidespredefineddatatypesthatmaptoPowerBuilderdatatypes,sothatyoucanusePowerBuilderdatatypeswhenyouinvokethemethodsofthenativeclass,andthenativeclasscanusepredefinedtypestocallbackintoPowerBuilder.Formoreinformationaboutpredefinedtypes,seeChapter6,"PBNITypesandReturnValues."YoucanusenativeclassestocallbackintothePBVMfromtheC++codeandtriggerPowerBuildereventsandinvokefunctions.Youcanalsocallexternalfunctionsthatrequirecallbackfunctions.Forexample,ifyour
PowerBuilderapplicationusesanextensionthatisaSAXXMLparser,theSAXparsercansendinformationbacktothePowerBuilderapplicationabouttheitemsithasencounteredintheXMLdocumentthatitisparsing.Inresponse,thePowerBuilderapplicationcansendbackinstructionsonhowtohandlethoseitems.Possibleusesforanonvisualextensioninclude:
AwrapperforaComponentObjectModel(COM)componentthatreferencesauser-definedCOMinterfacethatcannotbemappedtoaPowerBuilderdatatypeAPowerBuilderinterfacefordatabasebackupsandadministrationusingtheSQLAnywhere™dbtools(whichrequirecallbackfunctions)WrappersforanyopensourceC++librariesthatprovidestandardutilities
PowerBuilderextensionsrunfasterthanstandardPowerBuilderuserobjectsbecausetheyarecompiledinnativemachinecodeinsteadofPowerBuilderpseudocode(Pcode).PBNIcomplieswiththeC++specification,sowell–programmedcodeisportableatthesourcecodelevel.
VisualextensionsVisualextensionscanbeusedasiftheywerePowerBuildervisualuserobjects—youcanplacetheminwindowsoronothervisualcontrols.VisualextensionsallowyoutocreateasubclassoftheWindowsprocedure(winproc)ofavisualcomponentsothatyoucanusethelatest"lookandfeel"foryourapplications.
MarshalerextensionsMarshalerextensionsactasbridgesbetweenPowerBuilderandothercomponents,suchasEnterpriseJavaBeans(EJB)components,Javaclasses,Webservices,andCORBAcomponents.PowerBuilderprovidesamarshalerextensionforcreatingclientsforEJBcomponentsrunninginanyJ2EE–compliantapplicationserver.OthertechniquesforcallingEJBsfromPowerBuilderdonotprovideastandardwaytomarshalPowerBuilderrequeststoothercomponentsandunmarshaltheresultbacktoPowerBuilder.
EmbeddingthePBVMinaC++applicationManyPowerBuilderusershavedevelopedsophisticatedcustomclassuserobjectsthathandleintensivedatabaseoperationsorotherfunctionality.Suchobjectscanalreadybeusedinexternalapplications.However,limitationsontheuseofsomedatatypesandofoverloadedfunctions,aswellasothercodingrestrictions,diminishesthevalueofthistechnique.TohavedirectaccesstoacustomclassuserobjectrunninginthePBVM,andtotakeadvantageofPBNIfunctionsfordataaccessandexchange,youcanloadthePBVMintheC++application,createasession,andinvokethecustomclassuserobject'sfunctionsfromtheexternalapplication.CommunicationbetweenthePBVMandaC++applicationisbasedprimarilyontwointerfaces:IPB_VMandIPB_Session.
InteractingwithJavaTocallJavaclassesfromPowerBuilder,youcanbuildamarshalerextensionthatinvokesJavamethodsthroughJNI,asdescribedinChapter3,"CreatingMarshalerExtensions."YoucanalsouseJNItoallowJavatocallintoPowerBuilderthroughCorC++.Foranexample,seethePowerBuilderCodeXchangeWebsite.
TheelementsofPBNIToenablethefeaturesdescribedintheprevioussection,PBNIprovidesinterfaces,structures,globalfunctions,andhelperclasses.Theseelementsaredescribedinmoredetailinthereferencesectionofthisguide.SeeChapter7,"PBNIInterfaces,Structures,andMethods."Thissectionprovidesanoverview.
InterfacesTheIPB_VMinterfaceisusedtoloadPowerBuilderapplicationsinthird-partyapplicationsandinteroperatewiththePowerBuildervirtualmachine(PBVM).IPB_SessionisanabstractinterfacethatdefinesmethodsforperformingvariousactionssuchasaccessingPowerScriptdata,creatingPowerBuilderobjects,andcallingPowerScriptfunctions.TheIPB_ValueandIPB_ArgumentsinterfacesenableyoutopassvaluesbetweenthePowerBuilderVMandPowerBuilderextensionmodules.TheIPB_ValueinterfacerepresentsaPowerBuildervalue,whichcouldbeoneofthePowerBuilderstandarddatatypessuchasinteger,long,string,andsoforth.Itprovidesinformationabouteachvariable,includingitstype,nullflag,accessprivileges,arrayorsimpletype,andreferencetype.TheIPB_ArgumentsinterfacerepresentstheargumentspassedtoaPowerScriptfunctionandisusedtoaccessthedata.TheIPB_ResultSetAccessorandIPB_RSItemDatainterfacesenableyoutoaccessdatainaDataWindoworDataStore.AllPowerBuildernativeclassesinheritfromtheIPBX_NonVisualObjectinterfaceortheIPBX_VisualObjectinterface,whichinturninheritfromtheIPBX_UserObjectinterface.YoumustimplementtheInvokemethodintheinheritedclasstoenablePowerBuildertoinvokemethodsinthenativeclass.MarshalerextensionscontainaclassthatinheritsfromtheIPBX_Marshalerinterface.YoumustimplementtheInvokeRemoteMethodmethodintheinheritedclasstoenablePowerBuildertoinvokemethodsonremoteobjectsrepresentedbya
proxy.
StructuresThePBCallInfostructureholdsargumentsandreturntypeinformationforfunctioncallsbetweenPBNIandPowerBuilder.ToaccesstheinformationinPBCallInfo,usetheIPB_Argumentsinterface.ThePBArrayInfostructurestoresinformationaboutarrays.ThePB_DateData,PB_TimeData,andPB_DateTimeDatastructuresareusedtopassDataWindowandDataStoredata.
GlobalfunctionsEveryPowerBuilderextensionobjectmustexportglobalfunctionsthatenablethePowerBuilderVMtocreateinstancesoftheobjectanduseitsmethods.ThePBX_GetDescriptionfunctiondescribestheclassesandfunctionsintheextension.ThePBX_CreateNonVisualObjectfunctionenablesthePBVMtocreateinstancesofthenonvisualclassesinanextension,andthePBX_CreateVisualObjectfunctiondoesthesameforvisualclasses.
HelperclassesSeveralhelperclasses,suchasPBObjectCreator,PBArrayAccessor,andPBEventTrigger,makeiteasiertoprogramwithPBNI.
InteractionbetweenanextensionandthePBVMThefollowingdiagramsummarizeshowanextensioninteractswiththePBVM.Figure1-2:InteractionbetweenanextensionandthePowerBuilderVM
ThePBNISDKWhenyouinstallPowerBuilder,theSoftwareDevelopmentKit(SDK)forPBNIisinstalledinthePowerBuilder12.50\SDK\PBNIdirectory.TheSDKtools,pbsig125andpbx2pbd125,arealsoinstalledintheShared\PowerBuilderdirectorysothattheyareavailableinyourpath.TheSDKcontainsthecomponentsshowninthefollowingtable.
Table1-1:ContentsofthePBNISDK
Component Description
pbx2pbd125.exe
AtoolthatgeneratesaPBDfilefromaPowerBuilderextensionfile.TheextensionfileisaDLLfilethatmustexportasetofPBNIfunctions.TheDLLisusuallycalledaPBXandcanbegiventhesuffix.pbx.
pbsig125.exe
AtoolthatgeneratesasetofstringsrepresentingthereturntypeandargumentsofeachfunctioninaPBL.UsethesestringstocallPowerBuilderfunctionsfromexternalmodules.
include\pbni.hAheaderfilethatdefinesthestructuresandinterfacesusedtobuildPowerBuilderextensions.
include\pbarray.hAheaderfilethatcontainshelperclassesthatmakeiteasiertocreatearraysandaccessdatainthem.
include\pbfield.hAheaderfilethatcontainshelperclassesthatmakeiteasiertoaccessdatainfields.
include\pbtraits.h
Aheaderfileusedbypbarray.handpbfield.hthatprovidesspecializationsforthepbvalue_typeenumeratedtypes.
include\pbext.hAheaderfilethatdefinesthefunctionsthatPowerBuilderextensionfunctionsmustexport.
AheaderfilethatmapsthePowerBuildereventIDs
include\pbevtid.h toeventnamesforuseinvisualextensions.
include\pbnimd.hAheaderfilethatdefinesmachine-dependentdatatypesusedinpbni.h.
include\pbrsa.hAheaderfilethatdefinesinterfacesandstructuresusedtoaccessDataWindowandDataStoredata.
src\pbarray.cpp
Asourcefilethatmustbeaddedtoyourprojectifyouwanttousethefollowinghelperclassesdefinedinpbarray.h:
PBArrayAccessorPBObjectArrayAccessorPBBoundedArrayCreatorPBBoundedObjectArrayCreatorPBUnboundedArrayCreatorPBUnboundedObjectArrayCreator
src\pbfuninv.cpp
Asourcefilethatmustbeaddedtoyourprojectifyouwanttousethefollowinghelperclassesdefinedinpbni.h:
PBGlobalFunctionInvokerPBObjectFunctionInvokerPBEventTrigger
src\pbobject.cpp
Asourcefilethatmustbeaddedtoyourprojectifyouwanttousethefollowinghelperclassdefinedinpbni.h:PBObjectCreator.
wizards\VCProjects
8.0
AMicrosoftVisualStudio2005wizardthatmakesiteasierforyoutocreatePBNIprojects.
wizards\VCProjects
7.1
AMicrosoftVisualStudio.NET2003wizardthatmakesiteasierforyoutocreatePBNIprojects.
wizards\VCProjects
7.0
AMicrosoftVisualStudio.NET2002wizardthat
makesiteasierforyoutocreatePBNIprojects.
wizards\VCWizards FilesrequiredbytheVisualStudiowizards.
pbni125.hlp,pbni125.cnt
HelpfilesforPBNI.
ComparingPBNIandJNIIfyouhaveusedtheJavaNativeInterface(JNI),whichallowsJavaapplicationsandCandC++modulestointeroperate,youmightfindithelpfultobeawareofthesimilaritiesinthetwointerfacesandthedifferencesbetweenthem.TheIPB_VMinterfaceinPBNIisanalogoustotheJavaVMtype,andtheIPB_SessioninterfaceinPBNIisanalogoustoJNIEnv.ForJNI,youusethejavapcommandtoobtainastringthatencodesthesignatureofeachmethodinanativeclass.ForPBNI,thepbsig125toolperformsthesamefunction.Themajordifferencebetweenthetwointerfacesisinhowanativefunctionorclassisdeclared.InJNI,youmustusethenativekeywordtodeclarethatafunctionisnative,butyoucannotsimplydeclareaclassasnative.YoumustdefineyourclassesinJavasourcecode,usethejavahtooltogenerateaCheaderfilethatdefinesaCprototypeforeachnativemethod,thenimplementtheindividualCorC++functions,using#includetoincludethegeneratedheaderfile.PBNIprovidesanobject-orientedapproach—youdeclareaclassasnativeintheC++codebyinheritingfromtheIPBX_NonVisualObjectorIPBX_VisualObjectstruct.
BuildingPowerBuilderExtensions
AboutthischapterThischapterdescribeshowtobuildaPowerBuilderextension.Itbeginswithasampleapplicationthatusesasimplenonvisualextension.
ContentsTopic
Nonvisualextensionexample
CreatingaPowerBuilderextension
AddinganextensiontoaPowerBuildertarget
Usingtheextension
Creatingandusingavisualextension
Creatingvisualclassinstances
Eventprocessinginvisualextensions
CallingPowerScriptfromanextension
Exceptionhandlinganddebugging
NonvisualextensionexampleToillustratetheprinciplesinvolvedinbuildingandusinganextension,thischapterstartswithasampleapplicationthatusesaPowerBuilderextensiontoperformasimplearithmeticoperation.Ordinarily,thisisnotataskthatneedsPBNI,butitisusedheretomakethebasicprocessclear.Therestofthischapterdescribesbuildingextensionsinmoredetail.PBXfilesuffix
PowerBuilderextensionsareDLLfilesbuttypicallyusethefileextension.pbxinsteadof.dll.YourextensioniscompiledintoaPBXfilebydefaultifyouusethewizarddescribedinAppendixA,"UsingtheVisualStudioWizards"Formorerealisticexamples,seethePowerBuilderCodeXchangeWebsite.Thefollowingsampleapplicationhastwomainsteps:
BuildingthepbaddPowerBuilderextensionUsingtheextensioninPowerBuilder
BuildingthepbaddPowerBuilderextensionInthisexample,theC++codeisinthreefiles:
Theclassdeclarationisinaheaderfile,pbadd.hThestandardfunctionsthateveryPowerBuilderextensionmustexposeareinmain.cppTheimplementationoftheclassisinpbadd.cpp.
Toimplementthepbaddextension:1. Createthepbadd.hheaderfile.
Thepbadd.hheaderfiledeclaresthepbaddclass.Thefileincludespbext.h,whichmustbeincludedinallPowerBuilderextensionsbecauseitdeclarestheancestorclassesfornativeclassesandthestandardfunctionsthattheextensionmustexpose.Hereisthecodeforpbadd.h:#include"pbext.h"
classpbadd:publicIPBX_NonVisualObject
{
public:
pbadd();
virtual~pbadd();
PBXRESULTInvoke(
IPB_Session*session,
pbobjectobj,
pbmethodIDmid,
PBCallInfo*ci);
intf_add(IPB_Session*,pbint,pbint);
//Enumusedtoprovideentrypointsforeach
//methodintheclass-theonlyoneinthiscase
//ismAdd
enumMethodIDs
{
mAdd=0
};
private:
virtualvoidDestroy();
};
2. Createthemain.cppfile,whichincludespbadd.handimplementsthestandardfunctions,PBX_GetDescriptionand
PBX_CreateNonvisualObject:.PBX_GetDescriptionisusedtopassthedescriptionsofclassesintheextensiontoPowerBuilder.ThePBX_CreateNonVisualObjectmethodcreatestheobjectinstance.ThePowerScriptCREATEstatementmapstothisPBNImethod.
Thefollowingisthecodeformain.cpp:#include"pbadd.h"
//initializethePBX
BOOLAPIENTRYDllMain(HANDLEhModule,
DWORDul_reason_for_all,
LPVOIDlpReserved
)
{
switch(ul_reason_for_all)
{
caseDLL_PROCESS_ATTACH:
caseDLL_THREAD_ATTACH:
caseDLL_THREAD_DETACH:
caseDLL_PROCESS_DETACH:
break;
}
returnTRUE;
}
//describethepbaddclass
PBXEXPORTLPCTSTRPBXCALLPBX_GetDescription()
{
staticconstTCHARdesc[]={
"classpbaddfromnonvisualobject\n"\
"functionintf_add(inta,intb)\n"\
"endclass\n"
};
returndesc;
}
//exporttherequiredPBX_CreateNonVisualObject
//functionsothatthePBVMcan
//createaninstanceoftheclass
PBXEXPORTPBXRESULTPBXCALLPBX_CreateNonVisualObject
(
IPB_Session*pbSession,
pbobjectpbobj,
LPCSTRxtraName,
IPBX_NonVisualObject**obj
)
{
//ifthecallingfunctionrequeststhepbadd
//class,createaninstance
if(strcmp(xtraName,"pbadd")==0)
{
*obj=newpbadd;
}
return0;
};
3. Createthepbadd.cppfile,whichincludespbadd.handcontainstheimplementationofthepbaddclassanditssinglemethod,f_add.#include"pbadd.h"
//ImplementtherequiredInvokemethod
PBXRESULTpbadd::Invoke(IPB_Session*Session,
pbobjectobj,pbmethodIDmid,PBCallInfo*ci)
{
//ifthemethodtocallisf_add
if(mid==mAdd)
{
intsum=f_add(Session,ci->pArgs->GetAt(0)->
GetInt(),ci->pArgs->GetAt(1)->GetInt());
ci->returnValue->SetInt(sum);
}
returnPBX_OK;
}
//constructoranddestructor
pbadd::pbadd()
{
}
pbadd::~pbadd()
{
}
//implementtheclass'sf_addmethod
intpbadd::f_add(IPB_Session*session,pbintarg1,
pbintarg2)
{
returnarg1+arg2;
}
//ImplementtherequiredDestroymethod
voidpbadd::Destroy()
{
deletethis;
}
TocompileandlinkthePBX:1. InyourC++developmenttooloronthecommandline,compileand
linkthePBX.MakesuretheincludedirectoryinPowerBuilder12.5\SDK\PBNIisinyourincludepath.Forthisexample,thegeneratedDLLiscalledpbadd.pbx.
UsingtheextensioninPowerBuilderTousethePowerBuildernativeclassinaPowerBuilderapplication,importtheobjectdescriptionsinthePBXfileintoalibraryinyourapplication.Toimporttheextensionintoanapplication:
1. CopythePBX(orDLL)filetoadirectoryonyourapplication'spath.2. InPowerBuilder,createanewworkspace.3. OntheTargetpageoftheNewdialogbox,selecttheApplicationicon
tocreateanewtarget,library,andapplicationobject.4. IntheSystemTree,expandthenewtarget,right-clickthelibrary,and
selectImportPBExtensionfromthepop-upmenu.
5. Navigatetothelocationofthepbadd.pbxfileandclickOpen.Toinvokethef_addfunctioninPowerBuilder:
1. Createanewwindowcalledw_add,andaddthreesingle-lineeditboxesandacommandbuttontoit.
2. Declareaninstancevariablecalledmypbaddforthepbaddnativeclass,andthenaddthisscripttothebutton'sClickedevent:TRY
mypbadd=CREATEpbadd
sle_3.text=string(mypbadd.f_add(&
integer(sle_1.text),integer(sle_2.text)))
CATCH(runtimeerrorre)
MessageBox("Error",&
"pbaddnativeclasscouldnotbecreated:"+&
re.getmessage())
ENDTRY
ThepbaddclassdisplaysintheSystemTree.Asshowninthefollowingscreenshot,youcanexpanditsfunctionlist:
3. Addopen(w_add)totheapplication'sOpenevent.4. Runtheapplication.
TheapplicationrunsjustasitwouldifyouhadcreatedacustomclassuserobjectinPowerBuilderwithanf_addfunction.IfPowerBuildercannotfindpbadd.pbx,theruntimeerrorintheClickedeventscriptwillbetriggeredandcaught.Putpbadd.pbxinthesamedirectoryastheexecutableorthePowerBuilderruntimeDLLstomakesureitcanbefound.
CreatingaPowerBuilderextensionTobuildaPowerBuilderextension,followthesesteps:Step1:Decideonafeaturetoimplement.Step2:Definetheclassesandfunctionsintheextension.Step3:Declarenativeclassesandglobalfunctions.Step4:Implementnativeclassesandglobalfunctions.Step5:Exportmethodstocreateclassinstances.Step6:BuildaPBX.Thesestepsapplywhetheryouarebuildinganonvisualoravisualextension.Thedifferencesbetweenbuildingnonvisualandvisualextensionsaredescribedin"Creatingandusingavisualextension".Thissectionfocusesprimarilyonnonvisualextensions.
RequiredmethodsAllPowerBuildernonvisualextensionsmustexporttwomethods:PBX_GetDescriptionandPBX_CreateNonVisualObject.Theuseofthesemethodsisdescribedin"Step2:Definetheclassesandfunctionsintheextension"and"Step5:Exportmethodstocreateclassinstances".PowerBuildervisualextensionsmustexportPBX_GetDescriptionandPBX_CreateVisualObject.See"Creatingandusingavisualextension".Iftheextensiondeclaresglobalfunctions,itmustalsoexportthePBX_InvokeGlobalFunctionmethod.Foreverynativeclass,youmustimplementtwoPBNImethods,InvokeandDestroy,inadditiontothemethodstheclasswillprovide.TheuseofthesePBNImethodsisdescribedin"Step4:Implementnativeclassesandglobalfunctions".
Step1:DecideonafeaturetoimplementThefirststepinbuildingaPowerBuilderextensionistoidentifyaproblemthatanextensioncansolve.ThismightbeafeaturethatcanbecodedmoreefficientlyandeasilyinC++thaninPowerScript,orthatrequirestheuseofcallbackfunctionsornonstandarddatatypes.YoumightalsohaveaccesstoexistingC++classesthatperformthetasksyouwanttoaddtoaPowerBuilderapplication,oryoumightwanttocreateawrapperforexistingstandardutilitieswritteninC++.ForpossibleusesofPowerBuilderextensions,see"UnderstandingPowerBuilderextensions".ForexamplesofPowerBuilderextensions,seethePowerBuilderCodeXchangeWebsite.
Step2:DefinetheclassesandfunctionsintheextensionYourC++codemustexposetwostandardmethodsthatenablePowerBuildertorecognizeeachnativeclassandcreateinstancesoftheclass.OneofthesemethodsisPBX_GetDescription.UsePBX_GetDescriptiontopassthedescriptionsofclassesandglobalfunctionsinthePowerBuilderextensiontoPowerBuilder.Everyextensionmustexportthismethod.ImportingthePBXorDLLfileintoaPBLconvertsthedescriptionoftheextensionintoPowerScriptandaddsittothePBLassourcecode.ThekeywordnativeinthesourcecodeindicatesthatthePowerBuildertypewasdefinedinanextension.Alltheclassesorglobalfunctionsinanextensionmodulearepassedinasingledescription.Theexamplesthatfollowillustratehowyoudefineclassesandfunctionsinadescription.Forthefullsyntax,seePBX_GetDescription.
DescribingnonvisualclassesNonvisualclassescaninheritfromtheNonVisualObjectPowerBuildersystemclassoranyofitsdescendants.Whileanativeclasscaninheritfromauser–defineduserobject,Sybaserecommendsthatyouuseonlysystemclasses.Eachnativeclasscanprovideseveralfunctions,subroutines,andevents.ThefollowingexampleshowshowyouusethePBX_GetDescriptionmethodintheC++codeforanextensionthatincludesthreenonvisualclasses.ClassName1inheritsfromNonVisualObject,ClassName2inheritsfromException,andClassName3inheritsfromTransaction.AllthreeclassesmustbeinasingledescriptionpassedbyPBX_GetDescription:PBXEXPORTLPCTSTRPBXCALLPBX_GetDescription()
{
staticconstTCHARdesc[]={
//Descriptionbeginshere
"classClassName1fromNonVisualObject\n"
"functionintegerobjectFunction(integera[])\n"
"subroutineobjectSubroutine(integerai_ref)\n"
"eventintegereventName(integerb)\n"
"endclass\n"
"classClassName2fromException\n"
"functionintegerobjectFunction(readonly
integerai)\n"
"subroutineobjectSubroutine(integerarg)\n"
"eventintegereventName(integerarg)\n"
"endclass\n"
"classClassName3fromTransaction\n"
"functionintegerobjectFunction(integerarg)\n"
"subroutineobjectSubroutine(integerarg)\n"
"eventintegereventName(integerarg)\n"
"endclass\n"
//Descriptionendshere
};
returndesc;
}
DescribingvisualclassesVisualnativeclassescaninheritonlyfromtheUserObjectPowerBuildersystemclass.ThePowerBuilderVMconsidersanyclassthatinheritsfromUserObjecttobeavisualclass.Allothernativeclassesareconsideredtobenonvisualclasses.Formoreinformationabouthowtodescribevisualclasses,see"Creatingandusingavisualextension".
DescribingglobalfunctionsAnextensioncanincludeglobalfunctionsaswellasclasses.Thisexampleshowsadescriptionfortwoglobalfunctions:"globalfunctions\n"\
"functionintg_1(inta,intb)\n"\
"functionlongg_2(longa,longb)\n"\
"endglobalfunctions\n"
ThesyntaxandusageofglobalfunctionsdefinedinanextensionarethesameasforglobalfunctionsdefinedintheFunctionpainterinPowerBuilder.Globalfunctionscannotbeoverloaded
LikeglobalfunctionsinPowerScript,globalfunctionsinaPowerBuilderextensioncannotbeoverloaded.
UsingforwarddeclarationsPowerBuilderextensionscanprovidemultipleclasses.Aclasscanreferenceanyclassthatisdefinedearlierinthedescription,butifit
referencesaclassdefinedlaterinthedescription,youmustprovideaforwarddeclaration.Thisexampleshowsadescriptionthatincludesforwarddeclarationsfortwoclasses,nativeclass_1andnativeclass_2,thatreferenceeachother.Thisexamplealsodemonstratesthatasingledescriptioncanincludeglobalfunctionsaswellasclasses:"forward\n"\
"classnativeclass_1fromnonvisualobject\n"\
"classnativeclass_2fromnonvisualobject\n"\
"endforward\n"\
"classnativeclass_1fromnonvisualobject\n"\
"functionintadd(nativeclass_2a,intb)\n"\
"functionintsub(inta,intb)\n"\
"endclass\n"\
"classnativeclass_2fromnonvisualobject\n"\
"functionintadd(nativeclass_1a,intb)\n"\
"functionintsub(inta,intb)\n"\
"endclass\n"
"globalfunctions\n"\
"functionintg_1(inta,intb)\n"\
"functionlongg_2(longa,longb)\n"\
"endglobalfunctions\n"
Step3:DeclarenativeclassesandglobalfunctionsForeachnativeclassthatthenonvisualextensionsupports,declareanANSIC++classthatinheritsfromIPBX_NonVisualObject,whichistheancestorclassforallnonvisualPowerBuildernativeclasses.Thedeclarationoftheclasscanbeplacedinaheaderfile,anditmustincludeInvokeandDestroymethods.Thisisasimpleprototypeforanonvisualclass:#include"pbext.h"
classCMyClass:publicIPBX_NonVisualObject
{
enumMethodIDs
{
mFunca=0,
mFuncb=1
};
public:
//constructor,destructor
CMyClass()
virtual~CMyClass()
//membermethods
PBXRESULTInvoke(
IPB_Session*session,
pbobjectobj,
pbmethodIDmid,
PBCallInfo*ci
);
voidDestroy();
private:
voidfuncA(IPB_Session*session,pbobjectobj,
PBCallInfo*ci);
voidfuncB(IPB_Session*session,pbobjectobj,
PBCallInfo*ci);
};
Ifyoudeclareglobalfunctionsinyourextension,theextensionmustexportthePBX_InvokeGlobalFunctionmethod.ThefollowingPBX_GetDescriptioncalldeclaresthreeglobalfunctions:bitAnd,bitOr,andbitXor:PBXEXPORTLPCTSTRPBXCALLPBX_GetDescription()
{
staticconstTCHARdesc[]={
"globalfunctions\n"
"functionintbitAnd(inta,intb)\n"
"functionintbitOr(inta,intb)\n"
"functionintbitXor(inta,intb)\n"
"endglobalfunctions\n"
};
returndesc;
}
Step4:ImplementnativeclassesandglobalfunctionsTheimplementationofeachclassmustincludetheimplementationoftheInvokeandDestroymethods,aswellasallthemethodsdeclaredfortheclass.InvokeandDestroyaremethodsoftheIPBX_UserObjectinterface.WhenthePowerBuilderapplicationcallsamethodonthenativeclass,thePBVMcallstheInvokemethod,whichdispatchesthecallbasedonthemethodIDormethodname.Themethodnameisusedwhenthemethodiscalleddynamically.TheInvokemethodmustbecodedtoinvokeeachmethodintheclass.Theexamplethatfollowsshowsaswitch–casestatementthatinvokeseitherfuncAorfuncB,dependingonthevalueofthemethodID.WhenthePowerBuilderapplicationhasfinishedusinganinstanceofanativeclass,thePBVMcallstheDestroymethod.Thisexampledoesnotshowtheimplementationofthemethodsoftheclassitself:PBXRESULTMyClass::Invoke(IPB_Session*session,pbobjectobj,pbmethodIDmid,PBCallInfo*ci)
{
PBXRESULTresult=PBX_OK;
switch(mid)
{
casemFunca:
result=funcA(session,obj,ci);
break;
casemFuncb:
result=funcB(session,obj,ci);
break;
default:
result=PBX_E_INVOKE_FAILURE;
break;
}
returnresult;
}
//ImplementationoffuncAandfuncBnotshown
voidDestroy()
{
deletethis;
}
ThefollowingPBX_InvokeGlobalFunctioncontainstheimplementationofthethreeglobalfunctionsincludedinthedescriptionshownin"Step3:Declarenativeclassesandglobalfunctions":PBXEXPORTPBXRESULTPBXCALLPBX_InvokeGlobalFunction
(
IPB_Session*pbsession,
LPCTSTRfunctionName,
PBCallInfo*ci
)
{
PBXRESULTpbrResult=PBX_OK;
intarg1=ci->pArgs->GetAt(0)->GetInt();
intarg2=ci->pArgs->GetAt(1)->GetInt();
if(stricmp(functionName,"bitand")==0)
{
ci->returnValue->SetInt(arg1&arg2);
}elseif(strcmp(functionName,"bitor")==0)
{
ci->returnValue->SetInt(arg1|arg2);
}elseif(strcmp(functionName,"bitxor")==0)
{
ci->returnValue->SetInt(arg1^arg2);
}else
{
returnPBX_FAIL;
}
returnpbrResult;
}
Step5:ExportmethodstocreateclassinstancesPowerBuildercreatesnonvisualandvisualclassinstancesdifferently:
Forvisualclasses,theinstanceiscreatedwhenthewindoworvisualcontrolinwhichtheclassisusedisopened.See"Creatingvisualclassinstances".Fornonvisualclasses,theinstanceiscreatedwhenthePowerBuilderCREATEstatementisused.Thisisdescribednext.
WhenthePowerBuilderapplicationcreatesaninstanceofanonvisualclassusingthePowerScriptCREATEstatement,thePBVMcallsthePBX_CreateNonVisualObjectmethodintheextension.Everyextensionthatcontainsnonvisualnativeclassesmustexportthismethod.InthesamewaythatmultipleclassesareincludedinasingledescriptionpassedbyPBX_GetDescription,PBX_CreateNonVisualObjectcanbeusedtocreatemultipleclasses.Inthisexample,theextensionhasthreeclasses.AnIFstatementcomparesthenameoftheclasspassedinfromthePowerBuilderCREATEstatementtothenameofeachoftheclassesintheextensioninturnandcreatesaninstanceofthefirstclasswithamatchingname.YoucouldalsouseaCASEstatement.Theclassnameinthestringcomparisonmustbealllowercase:PBXEXPORTPBXRESULTPBXCALLPBX_CreateNonVisualObject(
IPB_Session*session,
pbobjectobj,
LPCSTRclassName,
IPBX_NonVisualObject**nvobj
)
{
PBXRESULTresult=PBX_OK;
//Theclassnamemustnotcontainuppercase
if(strcmp(className,"classone")==0)
*nvobj=newClassOne;
elseif(strcmp(className,"classtwo")==0)
*nvobj=newClassTwo(session);
elseif(strcmp(className,"classthree")==0)
*nvobj=newClassThree;
else
{
*nvobj=NULL;
result=PBX_E_NO_SUCH_CLASS;
}
returnPBX_OK;
};
Step6:BuildaPBXUsingyourC++developmenttoolorthecommandline,buildaPBXfromyourC++classes.WhenyoucompileandlinktheC++code,verifythefollowing:
TheincludedirectoryforthePBNISDK,typicallyPowerBuilder12.5\SDK\PBNI\include,mustbeinyourincludepath.Ifyouuseanyhelperclasses,makesurethesourcefilethatcontainsthemisaddedtoyourproject.Foralistofclasses,seethetablein"ThePBNISDK".
NowyouarereadytousetheextensioninaPowerBuilderapplication.
AddinganextensiontoaPowerBuildertargetThesimplestwaytoaddaPowerBuildernativeclasstoaPowerBuildertargetistoimporttheobjectdescriptionsinthePBXfileintoalibraryinthePowerBuilderSystemTree.Youcanalsouseacommand-linetooltocreateaPBDfilefromaPBXfileandaddittothetarget'slibrarysearchpath.Seepbx2pbd125.Toimportthedescriptionsinanextensionintoalibrary:
1. CopythePBXfileintoadirectoryontheapplication'spath.2. IntheSystemTree,expandthetargetinwhichyouwanttousethe
extension,right-clickalibrary,andselectImportPBExtensionfromthepop-upmenu.
3. NavigatetothelocationofthePBXfileandclickOpen.EachclassinthePBXdisplaysintheSystemTreesothatyoucanexpandit,viewitsproperties,events,andmethods,anddraganddroptoaddthemtoyourscripts.
Usingtheextension
UsingnonvisualclassesInPowerScript,usetheclassesinanonvisualextensionjustasyouwouldacustomclassuserobject:Declareaninstanceoftheobject,usetheCREATEstatementtocreatetheinstance,invoketheobject'sfunctions,anddestroytheinstancewhenyouhavefinishedwithit.Youcaninheritfromthenativeclassesifyouwanttoaddfunctionsoreventstotheclass.Atruntime,instancesofthenativeclassarecreatedasnormalPowerBuilderobjects.Inthisexample,theextensionmodulecontainstwononvisualnativeclasses:fontcallbackandfontenumerator.APowerBuildercustomclassuserobject,nvo_font,inheritsfromthefontcallbackclass.Thesestatementscreateinstancesofbothclasses:fontenumeratorfe
nvo_fontuf
fe=createfontenumerator
uf=createnvo_font
Afteraninstanceofanativeclasshasbeencreated,thePowerBuilderapplicationcancallmethodsontheobject.EachnativeclassmustimplementanInvokemethodthatthePowerBuilderVMcallswhenthePowerBuilderapplicationcallsoneofthenativeclass'smethods.Then,theInvokemethoddispatchesthemethodcallbasedonthemethodIDormethodname.Themethodnameisusedwhenanativemethodiscalleddynamically.Usingthepreviousexample,thisstatementinvokestheenumprinterfontsmethodoftheinstanceofthefontenumeratorclass:fe.enumprinterfonts(uf)
DestroyingthePBNIobjectinstanceWhenthePowerBuilderapplicationnolongerneedsaninstanceofanonvisualclassandaDESTROYstatementisissued,byeithertheuserorthegarbagecollector,orwhenthewindoworvisualcontrolthatcontainsavisualclassisclosed,thePowerBuilderVMdestroystheinstancebycallingthenativeclass'sDestroymethod.
CreatingandusingavisualextensionIngeneral,youfollowthesamestepstocreateanduseavisualextensionthatyoudotocreateanonvisualextension:Step1:Decideonafeaturetoimplement.Step2:Definetheclassesandfunctionsintheextension.Step3:Declarevisualclassesandglobalfunctions.Step4:Implementnativeclasses.Step5:Exportmethodstocreateclassinstances.Step6:BuildanduseaPBX.Step7:Usethevisualextensioninanapplication.UsingPowerBuildervisualobjectsinC++
ForinformationaboutusingPowerBuildervisualobjectsfromaC++application,see"ProcessingPowerBuildermessagesinC++".
Step1:DecideonafeaturetoimplementYoucanchoosetousevisualextensionstoimplementcontrolswithaspecificpurposeorthatuseacustomlookandfeel.Forsomeexamplesofvisualextensions,seethePowerBuilderCodeXchangeWebsite.
Step2:DefinetheclassesandfunctionsintheextensionThedescriptionforavisualclassfollowsthesamerulesasforanonvisualclass,butitmustinheritfromtheUserObjectsystemclass:PBXEXPORTLPCTSTRPBXCALLPBX_GetDescription()
{
staticconstTCHARdesc[]={
"classmyvisualextfromuserobject\n"
"subroutinefunc_1(intarg1,intarg2)\n"
"subroutinefunc_2(stringarga)\n"
"endclass\n"
};
returndesc;
}
Therearenoeventsintheprecedingexample,butatypicalvisualextensionmakesuseofeventssuchasmouseclicks.Therearetwowaystodeclareandhandleevents.See"Eventprocessinginvisualextensions".
Step3:DeclarevisualclassesandglobalfunctionsYoudeclarenativevisualclassesinthesamewayasnonvisualclasses,exceptthatyoudeclareanANSIC++classthatinheritsfromIPBX_VisualObject,whichistheancestorclassforallnonvisualPowerBuildernativeclasses,insteadoffromIPBX_NonVisualObject.Youcanalsodeclareglobalfunctionsinavisualextension.See"Step3:Declarenativeclassesandglobalfunctions"inthesectiononnonvisualextensions.
Step4:ImplementnativeclassesYouimplementInvokeandDestroymethodsandanyclassorglobalfunctionsthesamewayforvisualextensionsasfornonvisualextensions.See"Step4:Implementnativeclassesandglobalfunctions".
Step5:ExportmethodstocreateclassinstancesThemajordifferencebetweenvisualandnonvisualextensionsisinhowinstancesoftheclassarecreated.See"Creatingvisualclassinstances".
Step6:BuildanduseaPBXAsfornonvisualextensions,youmustbuildaPBX,importitintotheapplication,andputthePBXintheexecutionpath.See"Step6:BuildaPBX"and"AddinganextensiontoaPowerBuildertarget"inthesectiononnonvisualextensions.
Step7:UsethevisualextensioninanapplicationYoudonotneedtodeclareaninstanceofavisualclassorusetheCREATEstatementtocreateaninstance.ThePBVMcreatesaninstancewhenthewindoworvisualcontrolinwhichthevisualclassresidesisopened,asdescribedin"Creatingvisualclassinstances".Youcaninvoketheobject'sfunctionsthesamewaythatyouinvokeanonvisualobject'sfunctions.Touseavisualextension:
1. SelectFile>InheritfromthePowerBuildermenuandselectthePBDintheLibrarieslistintheInheritfromObjectdialogbox.
2. SelectthevisualclassandclickOK.3. IntheUserObjectpainter,sizethevisualobjectandmakeanyother
changesyouneed.4. Savetheobject.
YoucannowdragthenewuserobjectfromtheSystemTreedirectlyontoawindoworontoanothervisualcontrol,suchasatabcontrol,anduseitlikeanyothervisualuserobject.
CodesamplesThecodefragmentsintherestofthissectionarebasedoncompletesampleapplicationsthatyoucanfindonthePowerBuilderCodeXchangeWebsite.
CreatingvisualclassinstancesWhenthewindoworothervisualcontrolinwhichavisualnativeclassresidesiscreatedinaPowerBuilderapplication,thePBVMcallsthePBX_CreateVisualObjectmethodintheextensionautomatically—thePowerBuilderapplicationdeveloperdoesnotneedtowriteaCREATEstatementinascript.ThePBVMalsocallstheIPBX_VisualObject'sCreateControlmethod.EveryextensionthatcontainsvisualnativeclassesmustexportPBX_CreateVisualObjectandimplementCreateControl.ThefollowingissamplecodeforPBX_CreateVisualObject:PBXEXPORTPBXRESULTPBXCALLPBX_CreateVisualObject
(
IPB_Session*pbsession,
pbobjectpbobj,
LPCTSTRclassName,
IPBX_VisualObject**obj
)
{
PBXRESULTresult=PBX_OK;
stringcn(className);
if(cn.compare("visualext")==0)
{
*obj=newCVisualExt(pbsession,pbobj);
}
else
{
*obj=NULL;
result=PBX_FAIL;
}
returnPBX_OK;
};
RegisteringthewindowclassBeforeCreateControlcanbecalled,thewindowclassmustberegistered.ThiscodeusestheWindowsRegisterClassmethodtoregisterthewindowclasswiththeclassnames_className:voidCVisualExt::RegisterClass()
{
WNDCLASSwndclass;
wndclass.style=CS_GLOBALCLASS|CS_DBLCLKS;
wndclass.lpfnWndProc=WindowProc;
wndclass.cbClsExtra=0;
wndclass.cbWndExtra=0;
wndclass.hInstance=g_dll_hModule;
wndclass.hIcon=NULL;
wndclass.hCursor=LoadCursor(NULL,IDC_ARROW);
wndclass.hbrBackground=(HBRUSH)(COLOR_WINDOW+1);
wndclass.lpszMenuName=NULL;
wndclass.lpszClassName=s_className;
::RegisterClass(&wndclass);
}
YoumustalsoimplementtheWindowsUnregisterClassmethodtounregistertheclasswhenthewindowisclosed:voidCVisualExt::UnregisterClass()
{
::UnregisterClass(s_className,g_dll_hModule);
}
TheRegisterClassandUnregisterClassmethodsarecalledintheinitializationcodeforthePBX.ThisistheVisualC++DllMainmethod:BOOLAPIENTRYDllMain(HANDLEhModule,
DWORDreasonForCall,
LPVOIDlpReserved
)
{
g_dll_hModule=(HMODULE)hModule;
switch(reasonForCall)
{
caseDLL_PROCESS_ATTACH:
CVisualExt::RegisterClass();
break;
caseDLL_THREAD_ATTACH:
caseDLL_THREAD_DETACH:
break;
caseDLL_PROCESS_DETACH:
CVisualExt::UnregisterClass();
break;
}
returnTRUE;
}
ImplementingCreateControlEveryvisualnativeclassmustimplementtheIPBX_VisualObjectCreateControlmethod.AftergettingtheclassnamewiththeIPBX_VisualObjectGetClassNamemethod,CreateControlpassestheclassnametotheWindowsCreateWindowExmethodtocreatethewindow,thenreturnsthewindowhandletothePBVM:TCHARCVisualExt::s_className[]="PBVisualExt";
LPCTSTRCVisualExt::GetWindowClassName()
{
returns_className;
}
HWNDCVisualExt::CreateControl
(
DWORDdwExStyle,//extendedwindowstyle
LPCTSTRlpWindowName,//windowname
DWORDdwStyle,//windowstyle
intx,//horizontalpositionofwindow
inty,//verticalpositionofwindow
intnWidth,//windowwidth
intnHeight,//windowheight
HWNDhWndParent,//handletoparentor
//ownerwindow
HINSTANCEhInstance//handletoapplication
//instance
)
{
d_hwnd=CreateWindowEx(dwExStyle,s_className,
lpWindowName,dwStyle,x,y,nWidth,nHeight,
hWndParent,NULL,hInstance,NULL);
::SetWindowLong(d_hwnd,GWL_USERDATA,(LONG)this);
returnd_hwnd;
}
EventprocessinginvisualextensionsAvisualextensioncanhaveawindowprocedurethatcanprocessanyWindowsmessageoruser-definedmessage.ThePBVMpassesallsuchmessagestothevisualextension,whichcaninterceptmessagesandeitherprocessorignorethem.WindowProcisanapplication-definedcallbackfunctionthatprocessesmessagessenttoawindow.Intheexampleinthissection,aWM_PAINTmessageissenttotheextensionwhenanactioninthePowerBuilderapplicationcausesthewindowtoberedrawn.Whentheextensionreceivesthemessage,itrepaintsanareainthewindowusingthecurrentvaluesfortextandcolorsetbytheuseroftheapplication.Thefollowingexamplealsocapturesmouseclicksanddoubleclicks,andtriggerstheOnclickandOndoubleclickeventscriptsinthePowerBuilderapplication.Youcanusetwodifferentsyntaxesfordescribingevents:eventreturnTypeeventName(args_desc)newline
eventeventNamepbevent_tokennewline
UsinganeventnamewithreturntypeandargumentsThefollowingdescriptionusesthefirstsyntax.Theclasshastwoevents,onclickandondoubleclick:PBXEXPORTLPCTSTRPBXCALLPBX_GetDescription()
{
staticconstTCHARdesc[]={
"classvisualextfromuserobject\n"
"eventintonclick()\n"
"eventintondoubleclick()\n"
"subroutinesetcolor(intr,intg,intb)\n"
"subroutinesettext(stringtxt)\n"
"endclass\n"
};
returndesc;
}
CapturingmessagesandmouseclicksThecodeintheextensioncapturestheWindowsmessagesthatcausethewindowtobedrawn,aswellasmouseclicksanddoubleclicks:LRESULTCALLBACKCVisualExt::WindowProc(
HWNDhwnd,
UINTuMsg,
WPARAMwParam,
LPARAMlParam
)
{
CVisualExt*ext=(CVisualExt*)::GetWindowLong(hwnd,
GWL_USERDATA);
switch(uMsg){
caseWM_CREATE:
return0;
caseWM_SIZE:
return0;
caseWM_COMMAND:
return0;
caseWM_PAINT:{
PAINTSTRUCTps;
HDChdc=BeginPaint(hwnd,&ps);
RECTrc;
GetClientRect(hwnd,&rc);
LOGBRUSHlb;
lb.lbStyle=BS_SOLID;
//Getcolorusingthevisualclass'sGetColormethod
lb.lbColor=ext->GetColor();
HBRUSHhbrush=CreateBrushIndirect(&lb);
HBRUSHhbrOld=(HBRUSH)SelectObject(hdc,
hbrush);
Rectangle(hdc,rc.left,rc.top,rc.right-rc.left,
rc.bottom-rc.top);
SelectObject(hdc,hbrOld);
DeleteObject(hbrush);
//Gettextusingthevisualclass'sGetTextmethod
DrawText(hdc,ext->GetText(),
ext->GetTextLength(),&rc,
DT_CENTER|DT_VCENTER|DT_SINGLELINE);
EndPaint(hwnd,&ps);
}
return0;
//TriggereventscriptsinthePowerBuilderapplication
caseWM_LBUTTONUP:
ext->TriggerEvent("onclick");
break;
caseWM_LBUTTONDBLCLK:
ext->TriggerEvent("ondoubleclick");
break;
}
returnDefWindowProc(hwnd,uMsg,wParam,lParam);
}
TriggeringclickeventsThefollowingistheTriggerEventmethodthattriggerstheOnclickandOndoubleclickevents:voidCVisualExt::TriggerEvent(LPCTSTReventName)
{
pbclassclz=d_session->GetClass(d_pbobj);
pbmethodIDmid=d_session->GetMethodID(clz,
eventName,PBRT_EVENT,"I");
PBCallInfoci;
d_session->InitCallInfo(clz,mid,&ci);
d_session->TriggerEvent(d_pbobj,mid,&ci);
d_session->FreeCallInfo(&ci);
}
UsinganeventnamewithaPowerBuildereventIDAsimplerwaytotriggereventsinavisualextensionusesdirectmappingofWindowsmessagestoPowerBuilderevents.Thefollowingclassdescriptioncontainsthesametwoevents,butinthiscasetheyusethealternativesyntaxthatmapstheeventnametoaPowerBuildertokenname:PBXEXPORTLPCTSTRPBXCALLPBX_GetDescription()
{
staticconstTCHARdesc[]={
"classvisualextfromuserobject\n"
"eventonclickpbm_lbuttonup\n"
"eventondoubleclickpbm_lbuttondblclk\n"
"subroutinesetcolor(intr,intg,intb)\n"
"subroutinesettext(stringtxt)\n"
"endclass\n"
};
returndesc;
}
GeneratingeventsyntaxautomaticallyImportingtheextensiongeneratestheOnclickandOndoubleclickeventswiththeappropriateargumentsautomatically,andatruntime,thePBVMfirestheevents.YoudonotneedtocapturetheWindowsmessagesWM_LBUTTONUPandWM_LBUTTONDBLCLKintheextension.Inthefollowingdescription,onclickistheeventnameandpbm_lbuttonupistheeventtokenname.Noticethattheeventnameisnotfollowedbyemptyparenthesesasitiswhenyouusethereturntypeandargumentstechniquefordescribingtheevent:"eventonclickpbm_lbuttonup\n"
AboutthetokennameThetokennameisastringthatmapstoaninternalPowerBuildereventIDdefinedintheheaderfilepbevtid.h.ThefirstIDinthisfileisPB_NULL.ForallotherIDsinthefile,thereisafixedrelationshipbetweenthenamethatyouuseinthedescriptionandtheeventIDinpbevtid.h.ThenameisthesameastheIDwiththelettermappendedtothepbprefix.Youmustuselowercaseinthedescription.Forexample,theeventIDPB_ACTIVATEinpbevtid.hmapstothetoken
namepbm_activate.InthedescriptionprovidedwithPBX_GetDescription,youmustusethenamepbm_activate.Iftheeventnameyouprovidedoesnotexist,importingtheextensiongeneratesanerrormessage.Seethepbevtid.hfileforacompletelistofmappedIDs.
ProcessingeventssenttotheparentofthewindowSomeWindowsmessages,suchasWM_COMMANDandWM_NOTIFY,aresenttotheparentofanobjectandnottotheobjectitself.Suchmessagescannotbecaughtinthevisualextension'swindowprocedure.ThePBVMcallstheGetEventIDmethodtoprocessthesemessages,asfollows:
IfthemessageismappedtoaPowerBuilderevent,GetEventIDreturnstheevent'sidentifier,forexamplePB_BNCLICKED,andtheeventisfiredautomatically.Ifthemessageisnotmappedtoanevent,GetEventIDreturnsthevaluePB_NULLandthemessageisdiscarded.
Inthefollowingexample,theGetEventIDfunctionreturnstheidentifierPB_BNCLICKEDifaWM_COMMANDmessagewiththenotificationcodeBN_CLICKEDwassent.ItreturnstheidentifierPB_ENCHANGEifaWM_NOTIFYmessagewassent.Otherwise,itreturnsPB_NULL.TCHARCVisualExt::s_className[]="PBVisualExt";
LPCTSTRCVisualExt::GetWindowClassName()
{
returns_className;
}
HWNDCVisualExt::CreateControl
(
DWORDdwExStyle,//extendedwindowstyle
LPCTSTRlpWindowName,//windowname
DWORDdwStyle,//windowstyle
intx,//horizontalpositionofwindow
inty,//verticalpositionofwindow
intnWidth,//windowwidth
intnHeight,//windowheight
HWNDhWndParent,//handleofparentorownerwindow
HINSTANCEhInstance//handleofapplicationinstance
)
{
d_hwnd=CreateWindowEx(dwExStyle,s_className,
lpWindowName,dwStyle,x,y,nWidth,nHeight,
hWndParent,NULL,hInstance,NULL);
::SetWindowLong(d_hwnd,GWL_USERDATA,(LONG)this);
returnd_hwnd;
}
intCVisualExt::GetEventID(
HWNDhWnd,/*Handleofparentwindow*/
UINTiMsg,/*Messagesenttoparentwindow*/
WPARAMwParam,/*Wordparameterofmessage*/
LPARAMlParam/*Longparameterofmessage*/
)
{
if(iMsg==WM_COMMAND)
{
if((HWND)lParam==d_hwnd)
{
switch(HIWORD(wParam))
{
caseBN_CLICKED:
returnPB_BNCLICKED;
break;
}
}
}
if(iMsg==WM_NOTIFY)
{
returnPB_ENCHANGE;
}
returnPB_NULL;
}
CallingPowerScriptfromanextensionYoucancallPowerBuildersystemfunctionsthroughIPB_Session.TheInitCallInfomethodsimplifiestheprocessofsettingupthecallinformation.YouneedtoprovidetheargumentstotheInitCallInfomethod,includinganidentifierforthePowerBuilderfunctionyouwanttocall.TheidentifiercanbereturnedfromtheGetMethodIDorFindMatchingFunctionmethod.
UsingGetMethodIDTogetthefunction'sIDusingtheGetMethodIDmethod,youneedthefunction'ssignature:PbmethodIDGetMethodID(pbclasscls,LPCTSTR
methodName,PBRoutineTypert,LPCTSTRsignature);
Thesignatureargumentinthismethodcallisastringrepresentingthemethod'sreturntypeandarguments.YoucanobtainthisstringintheBrowser.Forexample,toobtainthesignatureofasystemfunction,selectsystemfunctionsfromtheleftpaneoftheSystempage,right-clickthefunctionintherightpane,andselectPropertiesfromitspop-upmenu:
Formethodsinyourapplication,youcanexpandtheobjectthatcontains
itintheSystemTree,selectthefunctionorevent,andselectPropertiesfromitspop-upmenu:
Considerthisfunction:of_get_trans(reftransactionatr_trans)returns(none)
ThesignatureforthisfunctionisQRCtransaction.Qindicatesthatthefunctiondoesnotreturnavalue,Rthattheargumentispassedbyreference,andCtransactionthattheargumentisaPowerBuildersystemobjectoftypetransaction.Youcanusethepbsig125command-linetooltoobtainafunction'ssignature.However,thepbsig125tooldoesnotreportthesignatureoffunctionsthatareinheritedfromanancestorobjectunlesstheyareextendedinthedescendant,anditdoesnotreporteventsignatures.Formoreinformationaboutusingpbsig125,andanexplanationofalltheformatsusedinthesignature,seepbsig125.
UsingFindMatchingFunctionInsteadofthestringthatGetMethodIDuses,theFindMatchingFunctionfunctionprovidesanotherwaytogetthemethodID.Someshortsignaturescanbedifficulttoparse,andsignaturesthatincludePowerBuildersystemobjectsorJavaclassescanbemuchlonger.
FindMatchingFunctionusesa"readablesignature"insteadofthestringusedbyGetMethodID:FindMatchingFunction(pbclasscls,LPCTSTRmethodName,PBRoutineType
ThereadableSignatureargumentisacomma-separatedlistoftheargumentsofthefunction.UnlikethestringusedbyGetMethodID,itdoesnotincludethereturntype.Forexample,forafunctioncalleduf_testthattakestwoarguments,anintbyvalueandadoublebyreference,thecalltoFindMatchingFunctionlookslikethis:mid=Session->FindMatchingFunction(cls,"uf_test",
PBRT_FUNCTION,"int,double");
InvokingPowerBuilderfunctionsThefollowingmethodsarethoseyouusemostfrequentlytoinvokePowerBuilderfunctions.Fordescriptionsofeachmethod,seeIPB_Sessioninterface.PbmethodIDGetMethodID(pbclasscls,LPCTSTRmethodName,
PBRoutineTypert,LPCTSTRsignature,pbbooleanpubliconly)
PBXRESULTInitCallInfo(pbclasscls,pbmethodIDmid,PBCallInfo*ci)
voidFreeCallInfo(PBCallInfo*ci)
PBXRESULTAdd<Type>Argument(PBCallInfo*ci,PBTypev);
PBXRESULTInvokeClassFunction(pbclasscls,pbmethodIDmid,
PBCallInfo*ci)
PBXRESULTInvokeObjectFunction(pbobjectobj,pbmethodIDmid,
PBCallInfo*ci)
PBXRESULTTriggerEvent(pbobjectobj,pbmethodIDmid,
PBCallInfo*ci)
Example:CallingPowerBuilderfunctionsInthiscodefragment,theclassandmethodIDreturnedbycallstotheIPB_SessionGetClassandGetMethodIDmethodsareusedtoinitializeaPBCallInfostructure,calledci,usingtheIPB_SessionInitCallInfomethod.Afteranewpbstringvariableiscreated,thevalueofthatstringissettothevalueofthefirstargumentinthePBCallInfostructure.BOOLCALLBACKCFontEnumerator::EnumFontProc
(
LPLOGFONTlplf,
LPNEWTEXTMETRIClpntm,
DWORDFontType,
LPVOIDuserData
)
{
UserData*ud=(UserData*)userData;
pbclassclz=ud->session->GetClass(ud->object);
pbmethodIDmid=ud->session->GetMethodID
(clz,"onnewfont",PBRT_EVENT,"IS");
PBCallInfoci;
ud->session->InitCallInfo(clz,mid,&ci);
//createanewstringvariableandsetitsvalue
//tothevalueinthefirstargumentinthe
//PBCallInfostructure
pbstringstr=ud->session->NewString
(lplf->lfFaceName);
ci.pArgs->GetAt(0)->SetString(str);
ud->session->TriggerEvent(ud->object,mid,&ci);
pbintret=ci.returnValue->GetInt();
ud->session->FreeCallInfo(&ci);
returnret==1?TRUE:FALSE;
}
ExceptionhandlinganddebuggingTohandleerrors,youusetheerrorcodesreturnedfromPBNImethods.SomefunctionsoftheIPB_Sessioninterfacereturndetailederrorcodesthatmakedebuggingeasier.Nativemethods,suchastheIPBX_UserObjectInvokemethod,returneitherPBX_OKorPBX_FAILiftheextensionencountersaseriousproblemfromwhichitcannotrecover.WheneverthePowerBuilderVMgetsPBX_FAILfromanativemethod,itthrowsaPBXRuntimeErrorinthePowerBuilderapplication.PBXRuntimeErrorinheritsfromthePowerBuilderRuntimeErrorsystemobjectandcanbecaughtandhandledinascriptinthesamewayasanyexceptioninPowerBuilder.Tocatchtheseerrors,wrapyourPowerScriptcallinatry-catchblockasfollows:TRY
n_cpp_pbniobjobj
obj=CREATEn_cpp_pbniobj
obj.of_test(arg1)
CATCH(PBXRuntimeErrorre)
MessageBox("Caughterror",re.getMessage())
ENDTRY
TheIPB_Sessioninterfaceprovidesasetofmethodstohandleexceptionsthatoccurinnativecode.UseHasExceptionThrowntodeterminewhetheranexceptionoccurred.Ifitdid,useGetExceptiontogetthecurrentexceptionobjectsothatitcanbehandled.Ifnecessary,youcanthrowexceptionstoPowerBuilderwithThrowException.Whenanexceptionhasbeenhandled,useClearExceptiontoclearit.
DebuggingYoucannoteditanativeclassinthePowerBuilderdevelopmentenvironment,andyoucannotenternativemethodsinthePowerBuilderdebuggerbecausethemethodsareC++methods.YoumustuseaC/C++debuggertodebuganextensionmodule.
CreatingMarshalerExtensions
AboutthischapterThischapterdescribeshowtocreatemarshalerextensions.
ContentsTopic
Aboutmarshalerextensions
DevelopingthePowerBuilderextension
GeneratingproxiesforJavaclasses
CallingtheJavaclassfromPowerBuilder
AboutmarshalerextensionsMarshalerextensionscanactasbridgesbetweenPowerBuilderandothercomponents,suchasEJBcomponents,Javaclasses,andWebservices,aslongasthosecomponentscanbecalledfromC++.Tocreateamarshalerextension,buildaPBXthatcontainsatleastoneclassthatimplementstheIPBX_Marshalerinterface,aswellasoneormorenativeclasses.Theextensionmustcontaincodethatassociatesthemarshalerwithaproxyforthecomponentyouwanttocall.Ifyoubuildamarshalerextension,youshouldalsoprovideatoolthatgeneratesproxiessothecomponentscanbecalledfromPowerBuilder.Forexample,PowerBuilderprovidesamarshalerextensionforcallingEJBcomponentsfromPowerBuilder,anditprovidesatoolforgeneratingproxiesforEJBcomponents.ThischapterprovidesanoverviewbasedontheJavaMarshalersampleapplication,whichcanbedownloadedfromthePowerBuilderCodeXchangeWebsite,andshowssomeextractsfromthesample.Thischapterdescribesthemajortasksinvolvedin:
DevelopingthePowerBuilderextensionGeneratingproxiesforJavaclassesCallingtheJavaclassfromPowerBuilder
Thischapterdoesnotshowdetailedcodesamples,andthefragmentsshownsimplifythecodinginvolved.Foramorecompleteunderstandingoftheprocessofbuildingamarshalerextension,downloadthesampleavailableontheWebsite.
DevelopingthePowerBuilderextensionAPowerBuildermarshalerextensionusuallyprovidesanativeclassthatactsasacreator.Thisclassdefinesafunctionthatcreatesaninstanceoftheforeigncomponentthatisspecifiedintheparameterspassedintothefunction(1).Ifitsucceedsincreatinganinstanceoftheforeigncomponent(2),itcreatesaproxyforitusingthePBVM(3,4),createsamarshalerobject(5),andassociatesthemarshalerwiththeproxy(6).Figure3-1:Creatingaforeigncomponent,proxy,andmarshaler
WhenafunctionoftheproxyobjectiscalledinPowerScript,thePBVMcallstheInvokeRemoteMethodfunctiononthemarshalerobjectthroughtheproxy(1,2).ThemarshalerobjecttranslatesPowerBuilderfunctioncallsintorequeststhattheforeigncomponentunderstands,sendstherequests(3),waitsforaresponse,andsendtheresultsbacktoPowerBuilder(4).Figure3-2:Invokingaremotemethod
Todeveloptheextension,youneedto:Step1:DescribetheextensionStep2:Implementthecreatorclass
Step3:Implementthemarshalerclass
Step1:DescribetheextensionTheclassthatimplementsthecreator,calledCJavaVMinthefollowingexample,mustexportthePBX_GetDescriptionfunction.ItinheritsfromNonVisualObjectandhastwofunctions,CreateJavaObjectandCreateJavaVM:PBXEXPORTLPCTSTRPBXCALLPBX_GetDescription()
{
staticconstTCHARdesc[]={
"classjavavmfromnonvisualobject\n"
"functionlongcreatejavavm(stringclasspath,
stringproperties[])\n"
"functionlongcreatejavaobject(refpowerobject
proxyobject,readonlystringjavaclassname,
readonlystringproxyname)\n"
"endclass\n"
};
returndesc;
}
Step2:ImplementthecreatorclassLikeanynonvisualnativeclass,theCJavaVMclassmustimplementtheInvokeandDestroyfunctionsinadditiontotheclassfunctionsCreateJavaObjectandCreateJavaVM.TheCreateJavaVmfunctionofCjavaVMgetstheclasspathandpropertiesfromthePBCallInfostructure.ThenitloadstheJavaVMbycallingtheloadJavaVMfunctionofawrapperclasscalledJavaVMWrapper.TheJavaVMWrapperclassencapsulatestheJavaVMinterfaceprovidedbyJNI.TheCreateJavaObjectfunctioncreatesaninstanceofaJavaclassbasedonthegivenclassname,createsaPowerBuilderproxyobjectfortheJavaobject,createsaJavaMarshalerobject,andassociatesthemarshalerobjectwiththeproxyobject.ThefollowingistheCreateJavaObjectfunction:PBXRESULTCJavaVM::CreateJavaObject
(
IPB_Session*session,
pbobjectobj,
PBCallInfo*ci
)
{
enum
{
kSuccessful=0,
kInvalidJavaClassName=-1,
kFailedToCreateJavaClass=-2,
kInvalidProxyName=-3,
kFailToCreateProxy=-4
};
//Getjavaclassname.
stringjclassName;
{
pbstringjcn=ci->pArgs->GetAt(1)->GetPBString();
if(jcn==NULL)
{
ci->returnValue->SetLong(kInvalidJavaClassName);
returnPBX_OK;
}
else
{
jclassName=session->GetString(jcn);
}
}
//Createjavaobject
JavaVMWrapper*jvm=JavaVMWrapper::instance();
JNIEnv*env=jvm->getEnv();
jclassjcls=env->FindClass(jclassName.c_str());
jobjectjobj=NULL;
if(jcls!=NULL)
{
JLocalReflrClz(env,jcls);
jmethodIDmid=env->GetMethodID(jcls,"<init>",
"()V");
if(mid!=NULL)
{
jobj=env->NewObject(jcls,mid);
}
}
//GetPowerBuilderproxyname
stringproxyName;
{
pbstringpn=ci->pArgs->GetAt(2)->GetPBString();
if(pn==NULL)
{
ci->returnValue->SetLong(kInvalidProxyName);
returnPBX_OK;
}
else
{
proxyName=session->GetString(pn);
}
}
//Findproxyclass
pbgroupgroup=session->FindGroup(proxyName.c_str(),
pbgroup_proxy);
if(group==NULL)
{
ci->returnValue->SetLong(kInvalidProxyName);
returnPBX_OK;
}
pbclasscls=session->FindClass(group,proxyName.c_str());
if(cls==NULL)
{
ci->returnValue->SetLong(kInvalidProxyName);
returnPBX_OK;
}
//CreatePowerBuilderproxyobject.
pbproxyObjectproxy=session->NewProxyObject(cls);
if(proxy==NULL)
{
ci->returnValue->SetLong(kFailToCreateProxy);
returnPBX_OK;
}
//CreateJavaMarshaler
JavaMarshaler*marshaler=newJavaMarshaler(env,
proxy,jobj);
//AssociatetheJavaMarshalerwiththeproxy
session->SetMarshaler(proxy,marshaler);
ci->pArgs->GetAt(0)->SetObject(proxy);
ci->returnValue->SetLong(kSuccessful);
returnPBX_OK;
}
Step3:ImplementthemarshalerclassThemarshalerclassmustimplementtheInvokeRemoteMethodfunction.ItalsoneedstoprovideaDestroyfunctionandgetthehandleofthemodule.Thisisthedeclaration:#include<jni.h>
#include<pbext.h>
classJavaMarshaler:publicIPBX_Marshaler
{
jobjectd_jobject;
pbproxyObjectd_pbobject;
public:
JavaMarshaler(JNIEnv*env,pbproxyObjectpbobj,jobjectejbobj);
~JavaMarshaler();
virtualPBXRESULTInvokeRemoteMethod
(
IPB_Session*session,
pbproxyObjectobj,
LPCSTRmethod_name,
PBCallInfo*ci
);
virtualpbulongGetModuleHandle();
virtualvoidDestroy();
};
TheInvokeRemoteMethodfunctioncallsJavafunctionsthroughJNI.ThisistheimplementationinJavaMarshaler.cpp:#include"JavaMarshaler.h"
#include"JMethod.h"
#include"JavaVMWrapper.h"
externpbulongg_dll_hModule;
pbulongJavaMarshaler::GetModuleHandle()
{
returng_dll_hModule;
}
//****************************************************
//JavaMarshaler
//****************************************************
JavaMarshaler::JavaMarshaler
(
JNIEnv*env,
pbproxyObjectpbobj,
jobjectejbobj
)
:d_jobject(env->NewGlobalRef(ejbobj)),
d_pbobject(pbobj)
{
}
JavaMarshaler::~JavaMarshaler()
{
JNIEnv*env=JavaVMWrapper::instance()->getEnv();
if(d_jobject!=NULL&&env!=NULL)
env->DeleteGlobalRef(d_jobject);
}
PBXRESULTJavaMarshaler::InvokeRemoteMethod
(
IPB_Session*session,
pbproxyObjectobj,
LPCSTRszMethodDesc,
PBCallInfo*ci
)
{
staticchar*eFailedToInvokeJavaMethod=
"FailedtoinvoketheJavamethod.";
JNIEnv*env=JavaVMWrapper::instance()->getEnv();
JMethodmethod(this,szMethodDesc);
try
{
if(d_jobject!=NULL)
{
method.invoke(session,env,d_jobject,ci);
if(env->ExceptionCheck()==JNI_TRUE)
{
stringerror(eFailedToInvokeJavaMethod);
error+="\n";
//Throwexceptionhere
returnPBX_E_INVALID_ARGUMENT;
}
}
}
catch(...)
{
}
returnPBX_OK;
}
voidJavaMarshaler::Destroy()
{
deletethis;
}
GeneratingproxiesforJavaclassesYouneedtodevelopPowerBuilderproxiesfortheJavaclassesyouwanttoinvokefromPowerBuilder.YoucandevelopproxiesusingJavareflection,fromJavasourcecodedirectly,orusingthejavaptool.Forexample,supposeyouwanttoinvokethisJavaclass:publicclassConverter
{
publicdoubledollarToYen(doubledollar);
publicdoubleyenToEuro(doubleyen);
}
ThePowerBuilderproxyforthisJavaclasscouldbestoredinafilecalledconverter.srxthatlookslikethis:$PBExportHeader$converter.srx
$PBExportComments$ProxygeneratedforJavaclass
globaltypeConverterfromnonvisualobject
endtype
globalConverterConverter
forwardprototypes
public:
functiondoubledollarToYen(doublead_1)alias
for"dollarToYen,(D)D"
functiondoubleyenToEuro(doublead_1)alias
for"yenToEuro,(D)D"
endprototypes
NoticethatbothPowerBuilderproxymethodshaveanaliascontainingtheJavamethodnameandmethodsignature.ThisisnecessarybecauseJavaiscasesensitive,butPowerBuilderisnot.TheextensionusesthealiasinformationisusedbytheextensiontofindthecorrespondingJavamethods.ToaddtheproxytoaPowerScripttarget,selectthelibrarywheretheproxywillbestoredintheSystemTree,selectImportfromthepop-upmenu,andbrowsetoselectconverter.srx.
CallingtheJavaclassfromPowerBuilderIntheopeneventofawindow,createaJavaVM://instancevariable:javavmi_jvm
stringproperties[]
i_jvm=createjavavm
stringclasspath
i_jvm.createjavavm(classpath,properties)
Intheclickedeventofabuttononthewindow,createaninstanceoftheConverterclassusingtheCreateJavaObjectmethodoftheJavaVMinstance,andcalltheconvmethodontheConverterclass:converterconv
doubleyen
i_jvm.createjavaobject(conv,"Converter","converter")
yen=conv.dollarToYen(100.0)
messagebox("Yen",string(yen))
WhentheCreateJavaObjectmethodiscalledinPowerScript,thePBVMcallsthecorrespondingC++methodintheextension.TheC++methodcreatesaJavaConverterobjectthroughJNI.Ifitissuccessful,themethodcreatesaninstanceofthePowerBuilderConverterproxyandaJavaMarshalerobject,andassociatestheJavaMarshalerobjectwiththePowerBuilderproxy.Whenconv.dollarToYen(100.0)iscalledinPowerScript,thePowerBuilderVMcallstheInvokeRemoteMethodmethodontheJavaMarshalerobject,whichdelegatesthecalltotheJavaConverterobjectthoughJNIandreturnstheresulttoPowerBuilder.
ExchangingDatawithPowerBuilder
AboutthischapterThischapterdescribeshowPBNIextensionsexchangedatawithPowerBuilder.
ContentsTopic
AboutexchangingdatawithPowerBuilder
PassingvaluesbetweenextensionsandthePBVM
UsingtheIPB_Sessioninterface
SavingdatafromIPB_Valuetoalocalvariable
Usingvariablesthroughoutasession
Handlingenumeratedtypes
AboutexchangingdatawithPowerBuilderYoucanusetheIPB_SessioninterfaceortheIPB_ValueandIPB_ArgumentsinterfacestoexchangedatabetweenPowerBuilderandPBNI.TheIPB_SessioninterfacecontainsmanyvirtualfunctionsthatenabletheC++codeinanextensiontointeractwiththePBVM.TheIPB_ValueandIPB_ArgumentsinterfacescontainmethodsthatyoucanusetopassvaluesbetweenPowerBuilderandextensions.
PassingvaluesbetweenextensionsandthePBVMPBNIusestwointerfaces,IPB_ValueandIPB_Arguments,topassPowerBuildervaluesbetweenthePBVMandextensionPBXs.ThePBNICallInfostructureholdsthedata.
PBCallInfostructureThePBCallInfostructureisusedtoholddataandreturntypeinformationforcallsbetweenextensionsandthePBVM.Ithasthreepublicmembers:IPB_Arguments*pArgs;
IPB_Value*returnValue;
pbclassreturnClass;
ThefollowingcodeinitializesaPBCallInfostructureusingtheIPB_SessionInitCallInfomethod.AfterallocatingaPBCallInfostructurecalledci,theIPB_SessionGetClassandGetMethodIDmethodsareusedtogettheclassandmethodIDofthecurrentmethod.Then,theseparametersareusedtoinitializethecistructure:pbclasscls;
pbmethodIDmid;
PBCallInfo*ci=newPBCallInfo;
cls=Session->GetClass(myobj);
mid=Session->GetMethodID(cls,"myfunc",
PBRT_FUNCTION,"II");
Session->InitCallInfo(cls,mid,ci);
WhenyouhavefinishedusingaPBCallInfostructure,youmustcallFreeCallInfotoreleasetheallocatedmemory:Session->FreeCallInfo(ci);
deleteci;
TheIPB_ArgumentsandIPB_ValueinterfaceshavemethodsthatenableyoutopassvaluesbetweenthePBVMandPowerBuilderextensionmodulesusingPBCallInfotoholdthedata.
IPB_ArgumentsinterfaceTheIPB_Argumentsinterfacehastwomethods:
GetCountobtainsthenumberofargumentsinamethodcall.GetAtobtainsthevalueataspecificindexofthepArgsmemberofthePBCallInfostructure.Foreachargument,GetAtreturnsapointertotheIPB_Valueinterface.
ThefollowingcodefragmentusesGetCountandGetAtinaFORlooptoprocessdifferentargumenttypes.Theci->pArgs->GetCount()statementgetsthenumberofarguments,andci->pArgs->GetAt(i)getsthevalueattheindexi.ThisvalueisapointertotheIPB_ValueinterfaceonwhichIPB_Valuemethods,suchasIsArrayandGetArray,canbecalled(see"IPB_Valueinterface"):inti;
for(i=0;i<ci->pArgs->GetCount();i++)
{
pbuintArgsType;
if(ci->pArgs->GetAt(i)->IsArray())
pArguments[i].array_val=
ci->pArgs->GetAt(i)->GetArray();
continue;
}
if(ci->pArgs->GetAt(i)->IsObject())
{
if(ci->pArgs->GetAt(i)->IsNull())
pArguments[i].obj_val=0;
else
pArguments[i].obj_val=
ci->pArgs->GetAt(i)->GetObject();
continue;
}
...
IPB_ValueinterfaceIPB_Valuehasthreesetsofmethods:helpermethods,setmethods,andgetmethods.
HelpermethodsTheIPB_Valueinterfacehelpermethodsprovideaccesstoinformationaboutvariablesandarguments,includingthevalue'sclassandtype,whetheritisanarrayorsimpletype,whetheritissetbyreference,andwhetherthenullflagisset.Thereisalsoamethodthatsetsthevaluetonull:virtualpbclassGetClass()const=0;
virtualpbintGetType()const=0;
virtualpbbooleanIsArray()const=0;
virtualpbbooleanIsObject()const=0;
virtualpbbooleanIsByRef()const=0;
virtualpbbooleanIsNull()const=0;
virtualPBXRESULTSetToNull()=0;
Theexampleshownintheprevioussection,"IPB_Argumentsinterface",showshowyoucanusethreeofthesemethods:IsArray,IsObject,andIsNull.ThisexampleshowshowyoucanusetheSetToNullmethodtosetthereturnValuememberofthePBCallInfostructuretonull:if(ci->pArgs->GetAt(0)->IsNull()||
ci->pArgs->GetAt(1)->IsNull())
{
//ifeitherofthepassedargumentsisnull,
//returnthenullvalue
ci->returnValue->SetToNull();
SetmethodsTheIPB_ValuesetmethodssetvaluesinthePBCallInfostructure.ThereisasetmethodforeachPowerBuilderdatatype:SetInt,SetUint,SetLong,SetUlong,andsoon.ThesemethodsautomaticallysetthevaluerepresentedbyIPB_Valuetonotnull.Thesyntaxis:virtualPBXRESULTSet<type>(<pbtype>arg);
Forexample,theSetLongmethodtakesanargumentoftypepblong.Inthisexample,themethodhastwointegerarguments,settoint_val1
andint_val2:ci->pArgs->GetAt(0)->SetInt(int_val1);
ci->pArgs->GetAt(1)->SetInt(int_val2);
TheIPB_ValuesetmethodssetthedatatypeofthevaluerepresentedbyIPB_Valuetoaspecifictype.Iftheoriginaltypeofthevalueisany,youcansetittoanyothertype.Then,becausethevaluenowhasaspecifictype,settingittoanothertypelaterreturnstheerrorPBX_E_MISMATCHED_DATA_TYPE.Iftheargumentisreadonly,theerrorPBX_E_READONLY_ARGSisreturned.
GetmethodsTheIPB_ValuegetmethodsobtainvaluesfromthePBCallInfostructure.ThereisagetmethodforeachPowerBuilderdatatype:GetInt,GetUint,GetLong,GetUlong,andsoon.Thesyntaxis:virtual<pbtype>Get<type>();
Forexample,theGetStringmethodreturnsavalueoftypepbstring.ThefollowingexampleusestheIPB_ValueGetAtmethodtoassignthevalueatthefirstindexofthepArgsmemberofthePBCallInfostructuretoavariableoftypeIPB_Value*calledpArg.IfpArgisnotnull,theGetLongmethodsetsthevariablelongvaltothevalueinpArg:PBCallInfo*ci
...
pblonglongval=NULL;
IPB_Value*pArg=ci->pArgs->GetAt(0);
if(!pArg->IsNull())
longval=pArg->GetLong();
Ifthevalueisnull,orifyouuseagetmethodthatisexpectedtoreturnonedatatypewhenthevalueisadifferentdatatype(suchasusingGetLongwhenthedatatypeispbarray),theresultreturnedisundetermined.ThegetmethodscanalsobeusedwiththereturnValuememberofPBCallInfo:ret_val=ci.returnValue->GetInt();
returnret_val;
UsingtheIPB_SessioninterfaceTheIPB_SessioninterfaceisanabstractinterfacethatenablesthePBVMtointeractwithPowerBuilderextensionsandwithexternalapplications.ItdefineshundredsofmethodsforaccessingPowerScriptvariables,callingPowerScriptmethods,handlingexceptions,andsettingamarshalertoconvertPowerBuilderdataformatstotheuser'scommunicationprotocol.TheIPB_Sessioninterfaceincludesseveralcategoriesofmethods:
ClassaccessormethodsareusedtofindPowerBuilderclasses,callPowerBuildermethodsandevents,andgetandsetinstancevariablesofPowerBuilderobjects.Exception-handlingmethodscommunicatewiththePowerBuilderexceptionhandlingmechanism.ArrayaccessormethodscreateandaccessPowerBuilderboundedandunboundedarrays.ResultsetaccessormethodsworkwithresultsetsinDataStoresandDataWindowcontrols.TypeddataaccessmethodscreateandaccessdataofthePowerBuildertypesstring,double,decimal,blob,date,time,datetime,andsoforth.Proxyaccessmethodsprovideaninterfacefortheimplementationofnewprotocols.TheReleasemethodreleasestheIPB_Sessionobjectitself.
Foracompletelistofmethods,seeIPB_Sessioninterface.YouuseIPB_SessionmethodsinconjunctionwithIPB_ValueandIPB_Argumentsmethods.ThefollowingcodefragmentshowsthebodyofamethodthattestswhetheradatepassedtoaPBNIfunctionishandledcorrectlybyaPowerBuilderfunction.ItusestheIPB_ValueSetToNull,SetDate,andIsNullmethodstosetandtestthedatevaluesinthePBCallInfostructure,aswellastheIPB_SessionSplitDate,SetDate,andNewDatemethods.//booleanisNull[],pbobjectmyobj,
//andpbdate*d_dateargumentspassedin
pbclasscls;
pbmethodIDmid;
PBCallInfo*ci=newPBCallInfo;
pbdateret_date;
pbintyy,mm,dd;
cls=Session->GetClass(myobj);
mid=Session->GetMethodID(cls,"uf_getdate_byref",
PBRT_FUNCTION,"YR");
Session->InitCallInfo(cls,mid,ci);
if(isNull[0])
ci->pArgs->GetAt(0)->SetToNull();
else
ci->pArgs->GetAt(0)->SetDate(*d_date);
Session->InvokeObjectFunction(myobj,mid,ci);
Session->SplitDate(ci->pArgs->GetAt(0)->GetDate(),
&yy,&mm,&dd);
Session->SetDate(*d_date,yy,mm,dd);
if(ci->returnValue->IsNull())
{
ret_date=Session->NewDate();
Session->SetDate(ret_val,1900,1,1);
}
else
{
ret_date=Session->NewDate();
Session->SplitDate(ci->returnValue->GetDate(),
&yy,&mm,&dd);
Session->SetDate(ret_val,yy,mm,dd);
}
Session->FreeCallInfo(ci);
deleteci;
returnret_date;
SavingdatafromIPB_ValuetoalocalvariableToavoidmemoryleaks,youmustcallFreeCallInfotofreethevaluesstoredinthePBCallInfostructureafterusingthestructure.However,aftermakingafunctioncall,youmightwanttosavethereturnvalueorabyreferenceargumentvalueintoalocalvariableyoucanuselater.TherearetechniquesforsavingvaluessotheyarestillavailableafterthecalltoFreeCallInfo.Howyousaveyourresultintoalocalvariabledependsonwhetheryouwanttosaveasimplevalue,apointervalue,oranobjectvalue.
SavingsimplevaluesSavingsimplevaluesisstraightforward.WhenyoucalloneoftheIPB_ValueGet<type>methodsforasimplevalue,suchasGetIntorGetReal,theactualdataisreturned.Asaresult,youcansimplysavethevaluesofanyofthefollowingdatatypes:
pbvalue_bytepbvalue_intpbvalue_uintpbvalue_longpbvalue_ulongpbvalue_realpbvalue_doublepbvalue_longlongpbvalue_booleanpbvalue_char
SavingpointervaluesApointervaluedoesnotcontaindata.Itcontainsapointertoamemorylocationwherethedataisstored.WhenyoucalloneoftheIPB_ValueGet<type>methodsforapointervalue,suchasGetBloborGetTime,itreturnsapointertomemorythatisalsopointedtobyIPB_Value.WhenyoucallFreeCallInfo,thememorytowhichIPB_Valuepointsis
releasedandthedataisdeleted.BecausethisisthesamedatapointedtobythepointerreturnedbytheGet<type>method,thatpointercannolongerbeusedtorepresentthedata.Thisappliestothefollowingpointervaluedatatypes,aswellastothepbarraydatatype:
pbvalue_decpbvalue_stringpbvalue_blobpbvalue_datepbvalue_timepbvalue_datetime
Ifyouwanttosavethedatainapointervalue,youcanusetheAcquireValue,AcquireArrayItemValue,andReleaseValuemethodstoacquireandreleasethedata.ThesemethodscloneanewIPB_ValuethatisnotfreeduntilyoucallReleaseValueandresettheexistingIPB_Valuepointer.Canbeusedforotherdatatypes
YoucanuseAcquireValueandAcquireArrayItemValuetoacquirevaluesofanydatatype.LiketheGet<type>methods,AcquireValueandAcquireArrayItemValuereturnapointertothememorywherethedataisstored,buttheyalsoresettheIPB_ValuepointersothatIPB_Valuenolongerpointstotheactualdata.WhenyoucallFreeCallInfo,thedatapointedtobythevalueacquiredusingAcquireValueandAcquireArrayItemValueisunaffected.Theoriginalvalueisresettozeroornull,soitcannolongerbeused.AttemptstogetoracquiretheoriginalvaluereturnzeroornulluntilanotherIPB_Valueissettothevalue.IftheIPB_ValueacquiredusingAcquireValueisanarray,theentirearrayisacquired.Toacquireonlyanelementofthearray,useAcquireArrayItemValue.Whenyouhavefinishedusingthedata,youmustfreethememoryusingtheReleaseValuemethod.TheprocessingthattheAcquireArrayItemValueandReleaseValuemethodsperformresultsinpoorperformancewhenhandlinglarge
arrays.Itismoreefficienttogetthetypeofthearrayandhandleeachtypewithappropriatetype–specificfunctions.Caution
YoumustcalltheReleaseValuemethodtofreethedata.Ifyoudonotdoso,amemoryleakwilloccur.YoumustnotcallReleaseValuetoreleaseapointerthatwasnotacquiredusingAcquireValueandAcquireArrayItemValue.DoingsomightcausethePBVMtocrash.
SavingobjectvaluesStrictlyspeaking,objectvaluesarealsopointervalues,butthePBVMhandlesthemdifferently.YouusetheIPB_SessionAddLocalRefandAddGlobalRefmethodstoaddareferencetotheobject.Ifthereisareferencetoanobject,itisnotdeletedwhenFreeCallInfoiscalled.Whenyounolongerneedtheobject,callRemoveLocalReforRemoveGlobalReftodecreasethereferencecountfortheobject.Ifthereferencecountisdecreasedtozero,theobjectisdeletedautomatically.ThereisanimportantdifferencebetweenAddLocalRefandAddGlobalRef.AreferenceaddedbyAddLocalRefcanbedeletedautomaticallywhenthelocalframeispoppedup.ThelocalframecanbepoppedbycallingPopLocalFrameorwhenthecurrentfunctionreturns.However,areferenceaddedbyAddGlobalRefisdeletedonlywhenRemoveGlobalRefiscalledorthesessionends.Youmustusethesemethodsinpairs;thatis,useRemoveLocalReftoremovereferencescreatedwithAddLocalRef,anduseRemoveGlobalReftoremovereferencescreatedwithAddGlobalRef.
UsingvariablesthroughoutasessionTheSetPropfunctionenablesyoutouseavariablevaluethroughoutanIPBsessionwithoutusingaglobalvariable,whichissusceptibletonamespaceconflictswithothersessions.SetPropisoneofasetofthreefunctions:
UseSetProptoregisteranewvariablewiththesessionortochangethevalueofanexistingvariable.UseGetProptoaccessthevariable.UseRemoveProptoremovethevariablefromthelistofvariablesassociatedwiththesessionwhenitisnolongerneeded.
ThissetoffunctionsisparticularlyusefulforworkingwithmultiplethreadsofexecutioninEAServer.SupposeyouwanttothrowanexceptionfromwithinaPBNIextensionandtheexceptionitselfisalsodefinedbythePBNIextension.YoucalltheIPB_SessionNewObjectfunctiontocreateaninstanceoftheexception,causingthePBX_CreateNonVisualObjectfunctiontobecalled.Onewaytosetthevalueofthefieldsoftheexceptionbeforethefunctionreturnsinathread–safemanneristocreateanewobjectorstructuretoholdtheexceptioninformationbeforecallingNewObject.YoucancallSetProptostorethestructureortheobjectinthecurrentIPB_Session.WhenPBX_CreateNonVisualObjectiscalled,youcancallGetProptogetthestructureorobjecttoobtaintheexceptioninformation,thencallRemoveProptoremovethedatayoustoredinthecurrentsession.Youcanalsousethesefunctionswheninitializinganduninitializingasession.IftheextensionexportsthePBX_NOTIFYfunction,thePBVMcallsPBX_NotifyimmediatelyafteranextensionPBXisloadedandjustbeforethePBXisunloaded.Youcanusethisfunctiontoinitializeanduninitializeasession.Forexample,youcouldcreateasessionmanagerobject,andstoreitintheIPBsessionusingtheSetPropfunction.Later,youcoulduseGetProptoobtainthesessionobject.
HandlingenumeratedtypesTheGetEnumItemValueandGetEnumItemNamefunctionsallowyoutoconvertthenameofanenumeratedvaluetoanintegervalue,andtoconvertanintegervaluetothenameofanenumeratedvalue.Thisexamplegetsthenumericvaluefortheboolean!enumeratedvalue,thenusesittoreturnthestringvalue:pblonglType=session->GetEnumItemValue("object",
boolean");//returns138
LPCTSTRszEnum=session->GetEnumItemName("object",
lType);//returns"boolean"
NoticethatthesecondargumentintheGetEnumItemValuecall,theenumeratedvalue,mustnothaveanappendedexclamationmark(!).ToreturnanenumeratedvaluefromanextensiontoPowerScript,usetheSetLongfunctiontosetthevalueoftheenumeratedvariableintoIPB_Value(youcannotuseSetIntorSetShort).Toobtainanenumeratedvariable'svalue,youcanuseGetIntorGetShortaswellasGetLong,aslongasthevalueisintheappropriaterange.Forexample,ifyouattempttouseGetInttoobtainavaluethatismorethan32767,thereturnedvalueistruncated.
CallingPowerBuilderfromC++
AboutthischapterAthird-partyapplicationorserverwritteninC++canloadthePowerBuilderVM,usePowerBuildernonvisualobjects,andusePowerBuildervisualcontrols.Thischapterusessomesimpleexamplestoillustratetheprocess.
ContentsTopic
AboutcallingPowerScriptfromC++applications
CallingPowerBuilderobjectsfromC++
Accessingresultsets
ProcessingPowerBuildermessagesinC++
MorePBNIpossibilities
AboutcallingPowerScriptfromC++applicationsIfyouhaveaPowerBuildercustomclassuserobjectthatperformsintensiveprogrammingthatwouldbeusefultoanapplicationthatyouneedtowriteinC++,youcanaccesstheobjectdirectlyfromtheC++applicationusingPBNI.YoudonotneedtomaketheuserobjectintoaCOMcomponentorautomationserver.TocallfunctionsonaPowerBuilderobject,youcanembedthePBVMintheC++application.TheC++applicationmustloadthePBVMbyloadingpbvm125.dllwiththeWindowsLoadLibraryfunction,getapointertotheIPB_VMinterfacebycallingthePB_GetVMfunctionexportedbypbvm125.dll,andcreateasessionbycallingtheIPB_VMCreateSessionfunction.TheapplicationcanthencreateaninstanceofthePowerBuilderclassandinvokeitsfunctionsthroughtheIPB_Sessioninterface.ThefollowingfigureillustratestherelationshipbetweentheC++applicationandtheinterfacesprovidedbythePBVM.Figure5-1:EmbeddingthePBVMinaC++application
CallingPowerBuilderobjectsfromC++ThissectionpresentsasimpleexamplethatillustrateshowtocallafunctiononaPowerBuildercustomclassuserobjectfromaC++application:
CreatingaPowerBuilderobjecttobecalledfromC++GettingthesignatureofafunctionCreatingtheC++applicationRunningtheC++application
CreatingaPowerBuilderobjecttobecalledfromC++Tokeepthecodeforthisexamplesimple,createanapplicationwithonecustomclassuserobjectthathasonefunction.Thefunctionreturnstheproductoftwointegers:1. InPowerBuilder,createanewworkspace.2. SelecttheApplicationiconfromtheTargetpageoftheNewdialog
boxandnametheapplicationloadpbvm.3. SelecttheCustomClassiconfromthePBObjectpageoftheNew
dialogbox.4. IntheFunctionprototypewindow,createafunctionwiththis
signature:f_mult(integerarg1,integerarg2)returnsinteger
5. Savetheuserobjectasnvo_multandclosetheUserObjectpainter.
GettingthesignatureofafunctionTowritetheC++codethatinvokesthef_multfunction,youneedtoobtainitsmethodID.ThemethodIDisusedtoinitializethePBCallInfostructureandtoinvokethefunction.TherearetwoIPB_SessionfunctionsthatreturnamethodID:GetMethodID,whichtakesasignature,andFindMatchingFunction,whichtakesacomma-separatedlistofarguments.YouusethesamefunctionswhenyoucallPowerScriptfromthecodeinyourextension;see"CallingPowerScriptfromanextension".IfyouwanttouseGetMethodID,youneedasignature.Thisfunctionissimpleenoughthatyoudonotneedatooltoobtainasignature—thesignatureisthestringIII,whichindicatesthatthefunctionreturnsanintegerandtakestwointegersasarguments.Formorecomplicatedfunctions,youcangetthesignaturefromtheSystemTreeorwiththepbsig125tool.
GettingasignaturefromtheSystemTreeTogetthesignatureoff_multintheSystemTree,expandnvo_mult,right-clickonthef_multfunction,andselectPropertiesfromthepop-upmenu.ThesignaturedisplaysinthePropertiesdialogboxintheSignaturetextbox:
Gettingasignatureusingpbsig125Togetthesignatureoff_multwithpbsig125,typethefollowingatacommandprompt:pbsig125d:\pbls\loadpbvm.pbl
Intheoutputofpbsig125,thecommentonthelastlinecontainsthesignaturetobepassedasthemethodIDargumenttoGetMethodID:PBObjectName:loadpbvm
PBObjectName:nvo_mult
publicfunctionintegerf_mult(integerarg1,
integerarg2)
/*III*/
Formoreinformationaboutthepbsig125toolandtheformatofmethodsignatures,seepbsig125.
CreatingtheC++applicationTocreatetheC++application,followthesesteps:1. LoadthePowerBuilderVM2. CallPB_GetVMtogetapointertotheIPB_VMinterface3. CreateanIPB_SessionobjectwithinIPB_VM4. CreateaninstanceofthePowerBuilderobject5. InitializethePBCallInfostructure6. CallthePowerBuilderfunction7. Writecleanupcode
LoadthePowerBuilderVM
InyourC++developmenttool,createanewconsoleapplicationproject.TheincludedirectoryforthePBNISDK,typicallyPowerBuilder12.5\SDK\PBNI\include,mustbeinyourincludepath.Ifyouuseanyhelperclasses,thesourcefilethatcontainsthemmustbeaddedtoyourproject.Foralistoffilesandhelperclasses,seethetablein"ThePBNISDK".ThecodefortheC++applicationcreatesanIPB_VMobjectusingthePB_GetVMfunctionandloadsthePowerBuilderVM:#include"pbext.h"
#include"stdio.h"
typedefPBXEXPORTPBXRESULT(*P_PB_GetVM)(IPB_VM**vm);
intmain(intargc,char*argv[])
{
IPB_Session*session;
IPB_VM*pbvm=NULL;
//LoadthePowerBuilderVMmodule
HINSTANCEhinst=LoadLibrary("pbvm125.dll");
if(hinst==NULL)return0;
fprintf(stderr,"LoadedPBVMsuccessfully\n");
CallPB_GetVMtogetapointertotheIPB_VMinterface
ThenextstepistocallthePB_GetVMfunctiontogetapointertotheIPB_VMinterface:P_PB_GetVMgetvm=(P_PB_GetVM)GetProcAddress
(hinst,"PB_GetVM");
if(getvm==NULL)return0;
getvm(&pbvm);
if(pbvm==NULL)return0;
CreateanIPB_SessionobjectwithinIPB_VM
NextcreateanIPB_SessionobjectwithinIPB_VM,usingthePowerBuilderapplication'snameandlibrarylistasarguments://loadpbvm.pblmustcontainanapplicationobject
//namedloadpbvmanditmustbeonthesearchpath
//fortheexecutablefile
LPCTSTRLibList[]={"loadpbvm.pbl"};
if(pbvm->CreateSession("loadpbvm",LibList,1,
&session)!=PBX_OK)
{
fprintf(stderr,"ErrorinCreateSession\n");
return1;
}
fprintf(stderr,"Createdsessionsuccessfully\n");
CreateaninstanceofthePowerBuilderobject
Afterthesessionhasbeencreated,theC++applicationcancreatePowerBuilderobjectsandcallPowerBuilderfunctionsinthatsession.YouusetheFindGroupfunctiontolocatethegroupthatcontainstheuserobjectyouwanttouse.FindGrouptakesthenameoftheobjectasitsfirstargument,andanenumeratedtypeasitssecondargument.Youarelookingforauserobject,sothesecondargumentispbgroup_userobject.YoupassthegroupreturnedfromFindGrouptotheFindClassfunctiontogetaclassthatyoucanpasstotheNewObjectfunction://CreatethePowerBuilderobjectcontained
//inloadpbvm.pbl.
//Firstfindthegroupthatcontainsthe
//userobjectnvo_mult
pbgroupgroup=session->FindGroup("nvo_mult",
pbgroup_userobject);
if(group==NULL)return0;
//Nowfindtheclassnvo_multinthegroup
pbclasscls=session->FindClass(group,"nvo_mult");
if(cls==NULL)return0;
//CreateaninstanceofthePowerBuilderobject
pbobjectpbobj=session->NewObject(cls);
InitializethePBCallInfostructure
Next,getthemethodIDforthefunctionyouwanttocallandinitializeaPBCallInfostructure.Youpassthesignatureobtainedin"Gettingthesignatureofafunction"totheGetMethodIDfunction://PBCallInfocontainsargumentsandreturnvalue
PBCallInfoci;
//Tocalltheclassmemberfunctionf_mult,
//passitssignatureasthelastargument
//toGetMethodID
pbmethodIDmid=session->GetMethodID(cls,"f_mult",
PBRT_FUNCTION,"III");
//InitializecallinfostructurebasedonmethodID
session->InitCallInfo(cls,mid,&ci);
YoucoulduseFindMatchingFunctioninsteadofGetMethodIDtogetthemethodID.Thecallwouldlooklikethis,becausef_multtakestwointegerarguments:pbmethodIDmid=session->FindMatchingFunction(cls,
"f_mult",PBRT_FUNCTION,"int,int");
CallthePowerBuilderfunction
Beforeyoucallthefunction,youmustsupplytheintegerstobemultiplied.Forthesakeofsimplicity,thefollowingcodesetsthemdirectlyinthePBCallInfostructure.//SetINarguments.Theprototypeofthefunctionis
//integerf_mult(integerarg1,integerarg2)
ci.pArgs->GetAt(0)->SetInt(123);
ci.pArgs->GetAt(1)->SetInt(45);
Finallycallthefunction,wrappingitinatry-catchstatementtohandleanyruntimeerrors://Callthefunction
try
{
session->InvokeObjectFunction(pbobj,mid,&ci);
//WasPBexceptionthrown?
if(session->HasExceptionThrown())
{
//HandlePBexception
session->ClearException();
}
}
catch(...)
{
//HandleC++exception
}
//Getthereturnvalueandprintittotheconsole
pbintret=ci.returnValue->GetInt();
fprintf(stderr,"Theproductof123and45is%i\n",
ret);
Writecleanupcode
WhenyouhavefinishedwiththePBCallInfostructure,callFreeCallInfotoreleasethememoryallocatedtoit,thendeletethestructure,releasethesession,andfreethelibrary://ReleaseCallInfo
session->FreeCallInfo(&ci);
delete&ci;
//Releasesession
session->Release();
return0;
FreeLibrary(hinst);
}
RunningtheC++applicationWhenyourunthecompiledexecutablefileatthecommandprompt,ifthePowerBuilderVMisloadedandthesessioniscreatedsuccessfully,thefollowingoutputdisplaysinthecommandwindow:LoadedPBVMsuccessfully
Createdsessionsuccessfully
Theproductof123and45is5535
AccessingresultsetsYoucanusetheIPB_ResultSetAccessorinterfacetoaccessresultsetsinPowerBuilder.UsetheIPB_SessionGetResultSetAccessormethodtocreateaninstanceoftheinterfaceusingaresultsetreturnedfromPowerBuilderasthemethod'sargument.YoucanthenusetheIPB_ResultSetAccessor'sgetColumnCount,GetRowCount,GetItemData,andGetColumnMetaDatamethodstoobtaininformationfromtheresultset.GetItemDatausestheIPB_RSItemDatainterfacetohandlethedataineachcellintheresultset.Ifthedatahasadate,time,ordatetimedatatype,itisstoredinaPB_DateData,PB_TimeData,orPB_DateTimeDatastructure.TocreatearesultsetthatcanbepassedtoPowerBuilder,usetheIPB_SessionCreateResultSetmethod.SeeCreateResultSetforanexample.
ProcessingPowerBuildermessagesinC++YoucanopenaPowerBuilderwindowfromaC++applicationorfromanextension,buttomakesurethateventstriggeredinthewindoworcontrolareprocessed,youneedtomakesurethattheC++applicationprocessesPowerBuildermessages.TheIPB_SessionProcessPBMessagefunctionletsyoudothis.EachtimetheProcessPBMessagefunctioniscalled,itattemptstoretrieveamessagefromthePowerBuildermessagequeueandprocessit.ThefunctionissimilartothePowerBuilderYieldfunction,whichyieldscontroltoothergraphicobjectsandpullsmessagesfromPowerBuilderobjectsandothergraphicobjectsfromthequeue.However,ProcessPBMessageprocessesonlyonemessageatatime,anditprocessesonlyPowerBuildermessages.MessagesareaddedtothePowerBuildermessagequeuewhenyoucallthePostEventfunction.
ProcessPBMessagemustbecalledrepeatedlyYouneedtomakesurethattheProcessPBMessagefunctioniscalledrepeatedly.FormostC++applications,youcanprovideamessageloopinthemainfunctionandinserttheIPB_SessionProcessPBMessagefunctioninthemessageloop.Thisisshownintheexamplethatfollows.IfyouuseMicrosoftFoundationClasses(MFC),youcannotmodifythebuilt–inmessageloop.ToensurethattheProcessPBMessagefunctioniscalledrepeatedly,youcanoverloadtheCWnd::WindowProcfunctionandinsertProcessPBMessageintotheoverloadedfunction:LRESULTCCallPBVCtrl::WindowProc(UINTmessage,
WPARAMwParam,LPARAMlParam)
{
d_session->ProcessPBMessage();
returnCDialog::WindowProc(message,wParam,lParam);
}
ExamplesThefollowingcodefragmentsarefromaC++programthatopensawindow.ThewindowhasamenuitemthatinvokestheOpeneventofaPowerBuilderapplication.
CallingProcessPBMessageThecalltoProcessPBMessageisinaloopintheWinMainfunction:int__stdcallWinMain(HINSTANCEhInstance,
HINSTANCEhPrevInstance,
LPSTRlpCmdLine,
intnCmdShow)
{
MSGmsg;
WNDCLASSEXwcex;
//initializationcodeomitted
...
RegisterClassEx(&wcex);
HWNDhWnd=CreateWindow(szWndClsName,
"OpenPBWindow",WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,0,CW_USEDEFAULT,0,NULL,NULL,
hInstance,NULL);
if(!hWnd)
{
returnFALSE;
}
ShowWindow(hWnd,nCmdShow);
UpdateWindow(hWnd);
try
{
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
//CalltoProcessPBMessage
if(session)
session->ProcessPBMessage();
}
}
catch(...)
{
MessageBox(NULL,"Exceptionoccurs",
"Exception",MB_OK);
}
returnmsg.wParam;
}
LoadingthePBVMandtriggeringaneventIntheWndProcfunction,whentheWM_CREATEmessageispassed,thePBVMisloadedandthelibrarylist,containingopenwin.pbl,ispassedtoCreateSession.WhentheuserselectsthemenuitemthatopensthePowerBuilderwindow,theFindGroup,FindClass,andGetMethodIDfunctionsobtaintheinformationneededtocreateanewapplicationobject,initializethePBCallInfostructure,andtriggertheapplicationobject'sOpenevent:LRESULTCALLBACKWndProc(HWNDhWnd,UINTmessage,
WPARAMwParam,LPARAMlParam)
{
intwmId,wmEvent;
PAINTSTRUCTps;
HDChdc;
switch(message)
{
caseWM_CREATE:
{
//LoadthePBVM
hPBVMInst=::LoadLibrary("pbvm125.dll");
P_PB_GetVMgetvm=(P_PB_GetVM)
GetProcAddress(hPBVMInst,"PB_GetVM");
IPB_VM*vm=NULL;
getvm(&vm);
//Definethelibrarylistandcreatethesession
staticconstchar*liblist[]={"openwin.pbl"};
vm->CreateSession("openwin",liblist,1,
&session);
break;
}
caseWM_COMMAND:
wmId=LOWORD(wParam);
wmEvent=HIWORD(wParam);
//Parsethemenuselections:
switch(wmId)
{
caseID_PB_VISUAL:
{
//InitializePBCallInfoandtriggerthe
//applicationopenevent
try
{
pbgroupgroup=session->FindGroup
("openwin",pbgroup_application);
pbclasscls=session->FindClass(group,
"openwin");
pbmethodIDmid=session->GetMethodID
(cls,"open",PBRT_EVENT,"QS");
pbobjectobj=session->NewObject(cls);
PBCallInfoci;
session->InitCallInfo(cls,mid,&ci);
session->TriggerEvent(obj,mid,&ci);
session->FreeCallInfo(&ci);
}
catch(...)
{
MessageBox(NULL,"Exceptionoccurs",
"Exception",MB_OK);
}
break;
}
default:
returnDefWindowProc(hWnd,message,wParam,
lParam);
}
break;
caseWM_PAINT:
hdc=BeginPaint(hWnd,&ps);
RECTrt;
GetClientRect(hWnd,&rt);
EndPaint(hWnd,&ps);
break;
caseWM_DESTROY:
session->Release();
session=NULL;
FreeLibrary(hPBVMInst);
PostQuitMessage(0);
break;
default:
returnDefWindowProc(hWnd,message,wParam,
lParam);
}
return0;
}
TestingProcessPBMessageYoucantesttheProcessPBMessagefunctionwithasimplePowerBuilderapplicationlikethisone:1. CreateaPowerBuilderapplicationcalledopenwininopenwin.pbl.2. Createamainwindow,w_main,withthreebuttons.3. Insertawindow-levelfunction,of_setcolor,thattakesthreeintegers
asargumentsandhasthisscript:this.backcolor=rgb(red,green,blue)
4. Insertawindow-leveluserevent,ue_test,withthisscript:MessageBox("ue_test","Thisisauserevent")
5. Providethefollowingscriptsfortheclickedeventsofthebuttons://cb_1:
MessageBox("Button1","Clicked")
parent.of_setcolor(255,255,0)
//cb_2:
MessageBox("Button2","Clicked")
parent.PostEvent("ue_event")//notfired
parent.of_setcolor(255,0,0)
//cb_3:
MessageBox("Button3","Clicked")
cb_1.PostEvent(Clicked!)//notfired
6. Scripttheapplication'sOpenevent:open(w_main)
WhentheProcessPBMessagefunctionisincludedintheC++application,theapplicationrunsfromC++asitdoesinPowerBuilder.Thepostedeventsincb_2andcb_3areprocessed.NowtrycommentingouttheselinesintheC++application,recompiling,andrunningtheapplicationagain:if(session)
session->ProcessPBMessage();
Themessageboxesstilldisplay(responsewindowshavetheirownmessageloop)andtheof_setcolorfunctioniscalled,butthepostedeventsdonotfire.
MorePBNIpossibilitiesTheabilitytocreatevisual,nonvisual,andmarshalerextensions,andtocallPowerBuilderobjectsfromexternalC++applications,opensupnumerousopportunitiestocombinethesecapabilitiestodevelopmorecomplexapplications.
WritinganextensionthatloadsthePBVMMostoftheexamplesinthisbookandonthePowerBuilderCodeXchangeWebsiteshowyouhowtocreateanextensioninC++anduseitinPowerBuilder,orhowtowriteaC++applicationthatloadsthePowerBuilderVM.YoucouldalsowriteanextensionthatloadsthePowerBuilderVMandusesacustomclassuserobject,usingthetechniquesdescribedinthischapter.ThefollowingfiguredepictstheinteractionbetweenthePBVMandanexternalapplicationthatusesanextension.Figure5-2:InteractionbetweenPBNI,thePBVM,andexternalapplications
CallingPowerBuilderfromJavaYoucancombinetheabilitytocallPowerBuilderclassesfromC++,asdescribedinthischapter,withtheabilitytocreatemarshalerextensions,asdescribedinChapter3,"CreatingMarshalerExtensions,"tocallPowerBuilderfromJava.OnewaytodothisistocreateaJavaproxyclassthatdeclaresstaticnativemethodsthatcanbecalledtoloadthePBVM,createPowerBuildersessions,createPowerBuilderobjects,andinvokePowerScriptfunctions.ThesenativemethodscancallintothePBVMthroughPBNI.AdditionalJavaclassesthatrepresentthePBVM,PowerBuildersessions,andPowerBuilderobjectscanbebasedontheproxyclass.TheJavaclassescalltheJavanativemethodsthroughJNI,whereastheJavanativemethodscallPowerBuilderthroughPBNI.ThereisasamplethatillustratesthesetechniquesonthePowerBuilderCodeXchangeWebsite.
ReferenceThispartcontainsreferenceinformationforPBNIdatatypes,interfaces,andtools.
PBNITypesandReturnValues
AboutthischapterThischaptercontainsinformationaboutthedatatypes,enumeratedtypes,anderrorreturnvaluesusedbythePowerBuilderNativeInterface.
ContentsTopic
PowerBuildertoPBNIdatatypemappings
TypesforaccesstoPowerBuilderdata
PBNIenumeratedtypes
Errorreturnvalues
PowerBuildertoPBNIdatatypemappingsThefollowingtablemapsPowerBuilderdatatypestopredefineddatatypesusedinPBNIC++modules.
Table6-1:Predefineddatatypemappings
PowerBuilderdatatypePredefineddatatype
Int pbint
Uint pbuint
Byte pbbyte
Long pblong
Longlong pblonglong
Ulong pbulong
Boolean pbboolean
Real pbreal
Double pbdouble
Decimal pbdec
Date pbdate
Time pbtime
DateTime pbdatetime
Char pbchar
Blob pbblob
String pbstring
Powerobject pbobject
TypesforaccesstoPowerBuilderdataThetypesinthefollowingtableenableaccesstoPowerBuilderdata.
Table6-2:TypesforaccesstoPowerBuilderdata
Datatype Description
pbgroup UsedtoaccessPowerBuildergroupinformation.AgroupisacontainerofPowerBuilderclasses.
pbclass UsedtoaccessPowerBuilderclassdefinitioninformation.
pbmethodIDUsedtoaccessthemethodIDofaPowerBuilderglobalormemberfunction.
pbfieldID Usedtoaccessaninstancevariable.
pbarray Usedtoaccessarrayinformationanddataitems.
PBNIenumeratedtypes
EnumeratedtypesforPowerBuildergroupsThepbgroup_typeenumeratedtypesareusedinIPB_SessionFindGroupcallstoidentifythetypeofgrouprequired.
Table6-3:EnumeratedtypesforPowerBuildergroups
Value PowerBuilderobject
pbgroup_application Application
pbgroup_datawindowDataWindowdefinition
pbgroup_function Globalfunction
pbgroup_menu Menu
pbgroup_proxy Proxydefinitionforaremoteobject
pbgroup_structure PowerBuilderstructuretype
pbgroup_userobject PowerBuilderuserobject
pbgroup_window Window
pbgroup_unknown Unknowngroup
EnumeratedtypesforPowerBuildervaluesThepbvalue_typeenumeratedtypesareusedinmethodssuchastheIPB_ValueGetTypemethodandtheIPB_SessionNewUnboundedSimpleArraymethodtoidentifythetypeofPowerBuilderdata.
Table6-4:EnumeratedtypesforPowerBuildervalues
Value PowerBuilderdatatype
pbvalue_notype Undetermineddatatype.
pbvalue_int Int
pbvalue_uint Uint
pbvalue_byte Byte
pbvalue_long Long
pbvalue_longlong Longlong
pbvalue_ulong Ulong
pbvalue_real Real
pbvalue_double Double
pbvalue_dec Decimal
pbvalue_string String
pbvalue_boolean Boolean
pbvalue_any Any(changedtoanotherdatatypewhensetexplicitly)
pbvalue_blob Blob
pbvalue_date Date
pbvalue_time Time
pbvalue_datetimeDateTime
pbvalue_char Char
EnumeratedtypesforPowerBuilderroutinesThepbrt_typeenumeratedtypesareusedinIPB_SessionGetMethodIDcallstoidentifythetypeofroutinerequired.
Table6-5:EnumeratedtypesforPowerBuilderroutines
forPowerBuilderroutines
Value Routinetype
PBRT_FUNCTIONFunction
PBRT_EVENT Event
ErrorreturnvaluesThefollowingtableshowsthePBXRESULTreturnvaluesanderrorcodesreturnedfromPBNImethods.
Table6-6:PBXResultreturnvalues
ValueofPBXResult Errorcode
PBX_OK 0
PBX_SUCCESS 0
PBX_FAIL -1
PBX_E_NO_REGISTER_FUNCTION -1
PBX_E_REGISTRATION_FAILED -2
PBX_E_BUILD_GROUP_FAILED -3
PBX_E_INVALID_ARGUMENT -4
PBX_E_INVOKE_METHOD_INACCESSABLE -5
PBX_E_INVOKE_WRONG_NUM_ARGS -6
PBX_E_INVOKE_REFARG_ERROR -7
PBX_E_INVOKE_METHOD_AMBIGUOUS -8
PBX_E_INVOKE_FAILURE -9
PBX_E_MISMATCHED_DATA_TYPE -10
PBX_E_OUTOF_MEMORY -11
PBX_E_GET_PBVM_FAILED -12
PBX_E_NO_SUCH_CLASS -13
PBX_E_CAN_NOT_LOCATE_APPLICATION -14
PBX_E_INVALID_METHOD_ID -15
PBX_E_READONLY_ARGS -16
PBX_E_ARRAY_INDEX_OUTOF_BOUNDS -100
PBNIInterfaces,Structures,andMethods
AboutthischapterThischaptercontainsreferenceinformationabouttheclasses,structures,andmethodsofthePowerBuilderNativeInterface.
ContentsTopic
Headerfilecontents
Classandinterfacesummary
IPB_Argumentsinterface
IPB_ResultSetAccessorinterface
IPB_RSItemDatainterface
IPB_Sessioninterface
IPB_Valueinterface
IPB_VMinterface
IPBX_Marshalerinterface
IPBX_NonVisualObjectinterface
IPBX_UserObjectinterface
IPBX_VisualObjectinterface
PBArrayInfostructure
PBCallInfostructure
PB_DateDatastructure
PB_DateTimeDatastructure
PB_TimeDatastructure
PBX_DrawItemStructstructure
PBArrayAccessortemplateclass
PBBoundedArrayCreatortemplateclass
PBBoundedObjectArrayCreatorclass
PBObjectArrayAccessorclass
PBUnboundedArrayCreatortemplateclass
PBUnboundedObjectArrayCreatorclass
Exportedmethods
MethodexportedbyPowerBuilderVM
HeaderfilecontentsPBNIclassesandinterfacesaredefinedinasetofheaderfiles.
pbni.hTheclasses,structures,andmethodsdefinedintheheaderfilepbni.hallowPowerBuilderextensionmodulestointeractwithPowerBuilder.Thisfilealsoincludesthepbarray.h,pbfield.h,andpbnimd.hheaderfiles.
pbarray.h,pbfield.h,pbtraits.h,andpbnimd.hpbarray.hcontainshelperclassesthatmakeiteasiertocreatearraysandaccessdatainthem.pbfield.hcontainsahelperclassthatmakesiteasiertoaccessfields.Bothheaderfilesrelyonpbtraits.h,whichprovidesspecializationsfortheValueenumeratedtypes.pbnimd.hcontainsmachine-specificdatatypedefinitions.Thesefilesshouldnotbeincludeddirectlyinyourcode.
pbext.hTheclasses,structures,andmethodsdefinedintheheaderfilepbext.hmustbeimplementedinPowerBuilderextensionmodulestoallowPowerBuilderapplicationstousetheextensionmodules.pbext.hincludespbni.handpbevtid.h.
pbevtid.hpbevtid.hcontainsmappingsfromPowerBuildereventstringstointernaleventidentifiers.ThesemappingsallowthePBVMtoautomaticallyfireeventsthatyouincludeinthedescriptionofanextension.Formoreinformation,see"Eventprocessinginvisualextensions".
pbrsa.hpbrsa.hcontainsstructuresandinterfacesusedtoaccessdatainDataStoresandDataWindowcontrols.
ClassandinterfacesummaryThistableliststheclassesandinterfacesthatmakeupPBNI.Afterthetable,theclassesandinterfacesarelistedinalphabeticalorder.Themethodsforeachclassarelistedinalphabeticalorderaftertheclassdescription.Severaladditionalhelperclassesthataredefinedinpbni.harenotlistedinthetable.Thesehelperclassesinclude:
PBArrayInfoHolderandPBCallInfoHolder–usedtoholdaPBArrayInfoorPBCallInfovariableandreleaseitwhenitisoutofscopePBEventTrigger,PBObjectFunctionInvoker,andPBGlobalFunctionInvoker–usedtotriggereventsandcallobjectandglobalfunctions
Table7-1:PBNIclassandinterfacesummary
Object DescriptionDefinedin
IPB_ArgumentsinterfaceUsedtoaccesstheargumentsofthePBCallInfostructure.
pbni.h
IPB_ResultSetAccessorinterface UsedtoaccessdatainaDataWindoworDataStore.
pbrsa.h
IPB_RSItemDatainterfaceUsedtosetdatavaluesinaresultsetfromaDataWindoworDataStore.
pbrsa.h
IPB_Sessioninterface
UsedtointeroperatewithPowerBuilder.Anabstractinterface,itdefinesmethodsforaccessingPowerScriptdata,callingPowerScriptfunctions,catchingandthrowing pbni.h
PowerScriptexceptions,andsettingamarshalertoconvertPowerBuilderdataformatstotheuser'scommunicationprotocol.
IPB_Valueinterface
UsedtoholdPowerBuilderdata,IPB_Valuecontainsinformationabouteachvariable,includingitstype,nullflag,accessprivileges,arrayorsimpletype,andreferencetype.
pbni.h
IPB_VMinterface
UsedtoloadPowerBuilderapplicationsinthird-partyapplicationsandinteroperatewiththePowerBuildervirtualmachine(PBVM).
pbni.h
PBArrayInfostructure Usedtoholdinformationaboutarrays.
pbni.h
PBCallInfostructure
UsedtoholdargumentsandreturntypeinformationinfunctioncallsbetweenPBNIandPowerBuilder.
pbni.h
PB_DateDatastructure
UsedtopassdataoftypeDateintheSetDatafunctionintheIPB_RSItemDatainterface.
pbrsa.h
PB_DateTimeDatastructure
UsedtopassdataoftypeDateTimeintheSetDatafunctionintheIPB_RSItemDatainterface.
pbrsa.h
PB_TimeDatastructureUsedtopassdataoftypeTimeintheSetDatafunctionintheIPB_RSItemDatainterface.
pbrsa.h
PBX_DrawItemStructstructure
UsedtoholdthepropertiesofanexternalvisualcontrolthatyouwanttodrawusingthePBX_DrawVisualObjectfunction.
pbext.h
PBArrayAccessortemplateclass Usedtoaccessitemsinanarray.
pbarray.h
PBObjectArrayAccessorclass Usedtoaccessitemsinanobjectarray.
pbarray.h
PBBoundedArrayCreatortemplateclass
Usedtocreateboundedarrays.
pbarray.h
PBBoundedObjectArrayCreatorclass
Usedtocreateboundedobjectarrays.
pbarray.h
PBBoundedObjectArrayCreatorclass
Usedtocreateunboundedarrays.
pbarray.h
PBUnboundedObjectArrayCreatorclass
Usedtocreateunboundedobjectarrays.
pbarray.h
IPBX_Marshalerinterface
UsedtoinvokeremotemethodsandconvertPowerBuilderdataformatstotheuser'scommunicationprotocol.AmarshalerextensionisaPowerBuilderextensionthatactsasthebridgebetweenPowerBuilderandothercomponents,suchas
pbext.h
EJBs,Javaclasses,CORBAobjects,Webservices,andsoon.
IPBX_NonVisualObjectinterface
InheritsfromIPBX_UserObjectandisthedirectancestorclassofnonvisualPowerBuildernativeclasses.
pbext.h
IPBX_UserObjectinterface
TheancestorclassofPowerBuildernativeclasses.Ithastwofunctions,DestroyandInvoke.
pbext.h
IPBX_VisualObjectinterface
InheritsfromIPBX_UserObjectandisthedirectancestorclassofvisualPowerBuildernativeclasses.
pbext.h
Exportedmethods
SomeexportedmethodsmustbeimplementedinPowerBuilderextensionmodules.
pbext.h
MethodexportedbyPowerBuilderVM
ThePB_GetVMmethodisexportedbythePowerBuilderVMandisusedtopasstheIPB_VMinterfacetotheuser.
pbni.h
IPB_Argumentsinterface:GetAtmethod
DescriptionReturnsapointertotheIPB_Valueinterfacerepresentinganargumentwhoseorderinthelistofargumentsisindicatedbyaspecifiedindex.
SyntaxGetAt(pbintindex)
Argument Description
index AvalidindexintothePBCallInfostructure
ReturnValuesIPB_Value*.
ExamplesInthefollowingcodefragment,GetAtobtainsthefirstvalueinthePBCallInfostructure.Thevaluehasbeenpassedinfromthecallingfunction.PBCallInfoci;
LPCSTRmyPBNIObj=NULL;
IPB_Value*pArg0=ci->pArgs->GetAt(0);
if(!pArg0->IsNull())
{
pbstringt=pArg0->GetString();
if(t!=NULL)
myPBNIObj=session->GetString(t);
}
SeeAlsoGetCount
IPB_Argumentsinterface:GetCountmethod
DescriptionObtainsthenumberofargumentsinaninstanceofPBCallInfo.
SyntaxGetCount()
ReturnValuespbint.
ExamplesThisexampleusesGetCountinaFORloopusedtoprocessdifferentargumenttypes:inti;
for(i=0;i<ci->pArgs->GetCount();i++)
{
pbuintArgsType;
if(ci->pArgs->GetAt(i)->IsArray())
pArguments[i].array_val=
ci->pArgs->GetAt(i)->GetArray();
continue;
}
if(ci->pArgs->GetAt(i)->IsObject())
{
if(ci->pArgs->GetAt(i)->IsNull())
pArguments[i].obj_val=0;
else
pArguments[i].obj_val=
ci->pArgs->GetAt(i)->GetObject();
continue;
}
...
SeeAlso
GetAt
IPB_ResultSetAccessorinterface:AddRefmethod
DescriptionWhenyoucalltheCreateResultSetfunctionofinterfaceIPB_Session,youneedtopassanargumentoftypeIPB_ResultSetAccessor.TheAddReffunctioniscalledonthatargumentandtheReleasefunctioniscalledwhenthepbobjectisdestroyed.
SyntaxAddRef()
ReturnValuesNone.
SeeAlsoCreateResultSet|GetColumnCount
IPB_ResultSetAccessorinterface:GetColumnCountmethod
DescriptionObtainsthenumberofcolumns.
SyntaxGetColumnCount()
ReturnValuesUnsignedlong.
ExamplesThisstatementstoresthenumberofcolumnsin*numCols:*numCols=d_rsAccessor->GetColumnCount();
SeeAlsoCreateResultSet|GetRowCount
IPB_ResultSetAccessorinterface:GetColumnMetaDatamethod
DescriptionObtainsacolumn'smetadata.Thecolumnnumberofthefirstcolumnis1.MemorymustbeallocatedforcolumnNamebeforethisfunctioncall.Thepointervaluescanbenull.
SyntaxGetColumnMetaData(unsignedlongcolumnNum,LPTSTRcolumnName,pbvalue_type*
Argument Description
columnNum Thenumberofthecolumnforwhichyouwanttoobtainmetadata
columnNameThenameofthespecifiedcolumn
type Apointertothetypeofthespecifiedcolumn
width Apointertothewidthofthespecifiedcolumn
ReturnValuesNone.
ExamplesThisexamplegetsthenumberofcolumnsinaresultsetandallocatesanarraytoholdthetypesofeachcolumn:CRsltSet::CRsltSet(IPB_ResultSetAccessor*rsAccessor)
:m_lRefCount(0),d_rsAccessor(rsAccessor)
{
rsAccessor->AddRef();
//foreachcolumn
ULONGnNumColumns=d_rsAccessor->GetColumnCount();
d_arrColTypes=newUSHORT[nNumColumns+1];
for(ULONGnColumn=1;nColumn<=nNumColumns;
++nColumn)
{
//getthecolumntypeintothearray
pbvalue_typetype;
d_rsAccessor->GetColumnMetaData(nColumn,
NULL,&type,NULL);
d_arrColTypes[nColumn]=(USHORT)type;
}
}
SeeAlsoCreateResultSet|GetColumnCount|GetItemData|GetRowCount
IPB_ResultSetAccessorinterface:GetItemDatamethod
DescriptionAccessesthedatainacell.Thefirstrowis1andthefirstcolumnis1.
SyntaxGetItemData(unsignedlongrow,unsignedlongcol,IPB_RSItemData*data
Argument Description
row Therownumberofthecell
col Thecolumnnumberofthecell
data ApointertoanIPB_RSItemDatastructure
ReturnValuesBoolean.
ExamplesThisexamplestoresthedatainthefirstrowandcolumnintheIPB_RSItemDatastructuresd:d_rsAccessor->GetItemData(1,1,&sd);
UsageIfthevalueofdataisnull,thisfunctionissuesthecallbackdata->SetNull.Ifthevalueisnotnull,itissuesthecallbackdata->SetData.Formoreinformation,examinetheIPB_RSItemDatainterface.
SeeAlsoCreateResultSet|GetColumnCount|GetColumnMetaData
|GetRowCount|IPB_RSItemDatainterface|SetData|SetNull
IPB_ResultSetAccessorinterface:GetRowCountmethod
DescriptionObtainsthenumberofrows.
SyntaxGetRowCount()
ReturnValuesUnsignedlong.
ExamplesThisstatementstoresthenumberofrowsin*numRows:*numRows=d_rsAccessor->GetRowCount();
SeeAlsoCreateResultSet|GetColumnCount|GetColumnMetaData|GetItemData
IPB_ResultSetAccessorinterface:Releasemethod
DescriptionWhenyoucalltheCreateResultSetfunctionofinterfaceIPB_Session,youneedtopassanargumentoftypeIPB_ResultSetAccessor.TheAddReffunctioniscalledonthatargumentandtheReleasefunctioniscalledwhenthepbobjectisdestroyed.
SyntaxRelease()
ReturnValuesNone.
SeeAlsoAddRef|CreateResultSet
IPB_RSItemDatainterface:SetDatamethod
DescriptionSetsthedatainanIPB_RSItemDatastructurewhentheGetItemDatafunctionofIPB_ResultSetAccessoriscalledandthedatavalueisnotnull.
SyntaxSetData(unsignedlonglen,void*data)
Argument Description
len Thelengthofthedata
data Avoidpointertotheaddressofthedata
ReturnValuesNone.
UsageIfthecelldatatypeis:
stringanddecimal,theaddresspointstoastringdate,theaddresspointstoaPB_DateDatastructuretime,theaddresspointstoaPB_TimeDatastructuredatetime,theaddresspointstoaPB_DateTimeDatastructureanotherdatatype,theaddresspointstodataofthecorrespondingtype
SeeAlsoGetItemData|SetNull
|PB_DateDatastructure|PB_DateTimeDatastructure|PB_TimeDatastructure
IPB_RSItemDatainterface:SetNullmethod
DescriptionSetsthedatainanIPB_RSItemDatastructuretonullwhentheGetItemDatafunctionofIPB_ResultSetAccessoriscalledandthedatavalueisnotnull.
SyntaxSetNull()
ReturnValuesNone.
SeeAlsoGetItemData|SetData
IPB_Sessioninterface:AcquireArrayItemValuemethod
DescriptionClonesthedatainthePBCallInfostructureinanarrayitemandresetstheIPB_Valuepointer.
SyntaxAcquireArrayItemValue(pbarrayarray,pblongdim[])
Argument Description
array Avalidpbarraystructure.
dimApblongarraytoholdtheindexesofalldimensionsofthearray.Thesizeofthearraymustequalthedimensionsofarray.
ReturnValuesIPB_Value*.
ExamplesThisFORloopacquiresthevalueofaniteminanarrayandsetsthevalueinanotherarray:for(i=1;i<=bound;i++)
{
dim[0]=i;
ipv=Session->AcquireArrayItemValue(refArg,dim);
Session->SetArrayItemValue(*i_array,dim,ipv);
Session->ReleaseValue(ipv);
}
UsageTheAcquireArrayItemValuemethodenablesyoutoretainthedatainthePBCallInfostructureforasinglearrayitem.
TheAcquireArrayItemValuemethodisindependentofthetypeofthedatabutismostusefulforacquiringthevalueofpointervalues,suchaspbvalue_string,pbvalue_blob,andsoon.WhenyoucallFreeInfo,thedataisnotfreedandthepointerreturnedbyAcquireArrayItemValueisstillvalid.Whenyounolongerneedthedata,youmustcalltheReleaseValuemethodtofreethedata.Failingtodosocausesamemoryleak.ThePBVMclonesanewIPB_Valueandresetstheexistingone.Ifyouattempttogetoracquiretheoriginalvalue,thevaluereturnediszeroornulluntilanotherIPB_Valueissettothevalue.Workingwithlargearrays
TheprocessingthattheAcquireArrayItemValueandReleaseValuemethodsperformresultsinpoorperformancewhenhandlinglargearrays.Itismoreefficienttogetthetypeofthearrayandhandleeachtypewithappropriatetype–specificfunctions.
SeeAlsoReleaseValue
IPB_Sessioninterface:AcquireValuemethod
DescriptionClonesthedatainthePBCallInfostructureandresetstheIPB_Valuepointer.
SyntaxAcquireValue(IPBValue*value)
Argument Description
value Thevaluetobereturned
ReturnValuesIPB_Value*.
ExamplesTheAcquireValuemethodisusedtoobtainamessageargumentvalue.Later,whenthevalueisnolongerneeded,itisreleasedusingReleaseValuetoavoidmemoryleaks://Acquireavalue
MessageArg=session->AcquireValue
(ci->pArgs->GetAt(0));
pbstringpbMessage=MessageArg->GetString();
Message=(LPSTR)session->GetString(pbMessage);
...
//Cleanupphase
if(MessageArg)
{
Session->ReleaseValue(MessageArg);
}
UsageTheAcquireValuemethodenablesyoutoretainthedatainthePBCallInfostructure.TheAcquireValuemethodisindependentofthetypeofthedatabutismostusefulforacquiringthevalueofpointer
valuessuchaspbvalue_string,pbvalue_blob,andsoon.WhenyoucallFreeInfo,thedataisnotfreedandthepointerreturnedbyAcquireValueisstillvalid.Ifthevalueacquiredisanarray,theentirearrayisacquired.Toacquireasingleelementinanarray,usetheAcquireItemValuemethod.Whenyounolongerneedthedata,youmustcalltheReleaseValuemethodtofreethedata.Failingtodosocausesamemoryleak.ThePBVMclonesanewIPB_Valueandresetstheexistingone.Ifyouattempttogetoracquiretheoriginalvalue,thevaluereturnediszeroornulluntilanotherIPB_Valueissettothevalue.
SeeAlsoAcquireArrayItemValue|ReleaseValue
IPB_Sessioninterface:Add<type>Argumentmethod
DescriptionAddsanargumentofaspecifictypeinavariableargumentPowerBuildercall.
SyntaxAddArrayArgument(PBCallInfo*ci,pbblobvalue,pbbooleanIsNull)
AddBlobArgument(PBCallInfo*ci,pbblobvalue,pbbooleanIsNull)
AddBoolArgument(PBCallInfo*ci,pbbooleanvalue,pbbooleanIsNull)
AddByteArgument(PBCallInfo*ci,pbbytevalue,pbbooleanIsNull)
AddCharArgument(PBCallInfo*ci,pbcharvalue,pbbooleanIsNull)
AddDateArgument(PBCallInfo*ci,pbdatevalue,pbbooleanIsNull)
AddDateTimeArgument(PBCallInfo*ci,pbdatetimevalue,pbbooleanIsNull
AddDecArgument(PBCallInfo*ci,pbdecvalue,pbbooleanIsNull)
AddDoubleArgument(PBCallInfo*ci,pbdoublevalue,pbbooleanIsNull
AddIntArgument(PBCallInfo*ci,pbintvalue,pbbooleanIsNull)
AddLongArgument(PBCallInfo*ci,pblongvalue,pbbooleanIsNull)
AddLongLongArgument(PBCallInfo*ci,pblonglongvalue,pbbooleanIsNull
AddObjectArgument(PBCallInfo*ci,pbobjectvalue,pbbooleanIsNull
AddPBStringArgument(PBCallInfo*ci,pbstringvalue,pbbooleanIsNull
AddRealArgument(PBCallInfo*ci,pbrealvalue,pbbooleanIsNull)
AddStringArgument(PBCallInfo*ci,LPCTSTRvalue,pbbooleanIsNull)
AddTimeArgument(PBCallInfo*ci,pbtimevalue,pbbooleanIsNull)
AddUintArgument(PBCallInfo*ci,pbuintvalue,pbbooleanIsNull)
AddUlongArgument(PBCallInfo*ci,pbulongvalue,pbbooleanIsNull)
Argument Description
ci ThePBCallInfotowhichtheargumentistobeadded.
value Thevaluetobeaddedtotheargumentsarray.
IsNull Indicateswhethertheargumentisnull.Thedefaultisfalse.
ReturnValuesPBXRESULT.PBX_OKonsuccess.
ExamplesThiscodeteststhataddinganintegerargumenttoaPBCallInfostructureciworkscorrectly:longCmy_pbni::f_Retrieve(IPB_Session*session,pbintretrieve_args,pbobjectdwobj)
{
pbclasscls;
pbmethodIDmid;
PBCallInfo*ci=newPBCallInfo;
pblongret_val;
PBXRESULTret;
cls=session->GetClass(dwobj);
mid=session->GetMethodID
(cls,"retrieve",PBRT_FUNCTION,"LAV");
if(mid==kUndefinedMethodID)
return-1;
session->InitCallInfo(cls,mid,ci);
ci->pArgs->GetAt(0)->SetInt(retrieve_args);
session->AddIntArgument(ci,retrieve_args,false);
ret=session->InvokeObjectFunction(dwobj,mid,ci);
if(ret!=PBX_OK)
ret_val=ret;
else
ret_val=ci->returnValue->GetLong();
session->FreeCallInfo(ci);
deleteci;
returnret_val;
}
UsageThiscallisusedinvariableargumentPowerBuildercalls,suchasdatawindow.retrieve(arg).Afterthecall,thevaluereturnedbyci->pArgs->GetCount()increasesbyone.
SeeAlsoGetCount|InvokeClassFunction|InvokeObjectFunction
IPB_Sessioninterface:AddGlobalRefmethod
DescriptionAddsaglobalreferencetothespecifiedPowerBuilderobject.
SyntaxAddGlobalRef(pbobjectobj)
Argument Description
obj AvalidPowerBuilderobjecthandle
ReturnValuespbclassornullonerror.
ExamplesThisexamplecheckswhetherareturnvalueisnull,andifitisnot,addsaglobalreferencetoittothesession:if(ci->returnValue->IsNull())
ret_val=0;
else
{
ret_val=ci->returnValue->GetObject();
Session->AddGlobalRef(ret_val);
}
SeeAlsoRemoveGlobalRef
IPB_Sessioninterface:AddLocalRefmethod
DescriptionAddsalocalreferencetothespecifiedPowerBuilderobject.
SyntaxAddLocalRef(pbobjectobj)
Argument Description
obj AvalidPowerBuilderobjecthandle
ReturnValuespbclassornullonerror.
ExamplesThisexampledefinesfunctionsthataddandremovelocalreferences:voidMyPBNIClass::reference()
{
d_session->AddLocalRef(d_pbobject);
}
voidMyPBNIClass::unreference()
{
if(d_pbobject!=NULL)
d_session->RemoveLocalRef(d_pbobject);
}
SeeAlsoPopLocalFrame|PushLocalFrame|RemoveLocalRef
IPB_Sessioninterface:ClearExceptionmethod
DescriptionClearsthecurrentPowerBuilderexceptionobject.
SyntaxClearException()
ReturnValuesNone.
UsageHasExceptionThrownreturnsfalseafteracalltoClearException.Ifnoexceptionhasbeenthrown,thiscallhasnoeffect.
SeeAlsoGetException|HasExceptionThrown|ThrowException
IPB_Sessioninterface:CreateResultSetmethod
DescriptionCreatesaresultsetobjectusingapointertoanIPB_ResultSetAccessorobject.
SyntaxCreateResultSet(IPB_ResultSetAccessor*rs)
Argument Description
rs ApointertoanIPB_ResultSetAccessorobject
ReturnValuespbobject.
ExamplesThisexampleloadsthePBVMandcallsthef_retandf_infunctionsinthecustomclassuserobjectn_rsinthePBLpbrs.pbl.ThePowerScriptforthefunctionsisshownaftertheC++code:#include"stdafx.h"
#include"windows.h"
#include"pbni.h"
#include"vector"
usingstd::vector;
voidmain(intargc,char*argv[])
{
HINSTANCEhinst=LoadLibrary("pbvm125.dll");
typedefPBXRESULT(*P_PB_GetVM)(IPB_VM**vm);
P_PB_GetVMgetvm=(P_PB_GetVM)GetProcAddress(hinst,
"PB_GetVM");
IPB_VM*pbvm;
getvm(&pbvm);
IPB_Session*session=NULL;
vector<LPCSTR>ll(1);
ll[0]="pbrs.pbl";
pbvm->CreateSession("pbrs",&ll[0],1,&session);
pbgroupgroup=session->FindGroup("n_rs",
pbgroup_userobject);
if(group==NULL)return;
pbclasscls=session->FindClass(group,"n_rs");
if(cls==NULL)return;
pbobjectobj=session->NewObject(cls);
if(obj==NULL)return;
pbmethodIDmid=session->GetMethodID(cls,"f_ret",
PBRT_FUNCTION,"Cresultset.");
PBCallInfoci;
session->InitCallInfo(cls,mid,&ci);
session->InvokeObjectFunction(obj,mid,&ci);
//Usetheresultsetreturnedfromf_retto
//createanIPB_ResultSetAccessorrsa
pbobjectrs=ci.returnValue->GetObject();
IPB_ResultSetAccessor*rsa=
session->GetResultSetAccessor(rs);
//Createaresultsetobjectfromrsa
pbobjectrsobj=session->CreateResultSet(rsa);
//Callthef_inmethod
mid=session->GetMethodID(cls,"f_in",
PBRT_FUNCTION,"IRCresultset.");
PBCallInfoci1;
session->InitCallInfo(cls,mid,&ci1);
//Settheresultsetobjectrsobjasthe
//argumentforf_in
ci1.pArgs->GetAt(0)->SetObject(rsobj);
session->InvokeObjectFunction(obj,mid,&ci1);
session->FreeCallInfo(&ci);
session->FreeCallInfo(&ci1);
}
f_retretrievesdatafromadatabaseintoaDataStoreandgeneratesaresultset:ResultSetrs
DataStoreds
Longsts
Integerli_ret
//ProfileEASDemoDBV125
SQLCA.DBMS="ODBC"
SQLCA.AutoCommit=False
SQLCA.DBParm=&
"ConnectString='DSN=EASDemoDBV125;UID=dba;PWD=sql'"
connectusingsqlca;
ds=CreateDataStore
ds.DataObject=""
ds.DataObject="d_rs"
ds.SetTransObject(sqlca)
w_main.dw_1.SetTransObject(sqlca)
longll_ret,rows,rows2
ll_ret=ds.Retrieve()
ll_ret=w_main.dw_1.Retrieve()
//ds.sharedata(w_main.dw_1)
rows=ds.RowCount()
rows2=w_main.dw_1.RowCount()
messagebox("infofromf_ret","rowcountis"&
+string(rows)+"or"+string(rows2))
sts=ds.GenerateResultSet(rs)
Returnrs
f_intakesaresultset,rs,asanargumentandusesittocreateaDataStore:DataStoreds
Intcnt,li_ret
ds=CreateDataStore
ds.CreateFrom(rs)
cnt=ds.RowCount()
messagebox("infofromf_in","rowcountis"+string(cnt))
Returncnt
UsageTousetheIPB_ResultSetAccessorinterface,loadthePBVM,obtaina
resultsetfromaPowerBuilderapplication,andcallGetResultSetAccessoronthisresultsettogetanIPB_ResultSetAccessorinterfaceobject.Youcanthencallthemethodsofthisobjecttogetinformationabouttheresultset.YoucanalsocallCreateResultSetusingthisobjectasanargumenttocreatearesultsetthatyoucanreturntoPowerBuilder.WhenyoucallCreateResultSet,theAddReffunctionoftheIPB_ResultSetAccessorinterfaceiscalledonthersargumentimplicitlytoaddareferencetotheinterfacepointer.
SeeAlsoAddRef|GetResultSetAccessor|IPB_ResultSetAccessorinterface|ReleaseResultSetAccessor
IPB_Sessioninterface:FindClassmethod
DescriptionSearchesforaclasswithagivennamewithinagivengroup.
SyntaxFindClass(pbgroupgroup,LPCTSTRname)
Argument Description
group Thehandleofthegroupinwhichtheclassresides
name Theclassnameinlowercase
ReturnValuespbclassornullonfailure.
ExamplesThisexamplefindsthegroupassociatedwiththef_getrowfunctionandusesthegrouptofindtheclass:group=session->FindGroup("f_getrow",
pbgroup_function);
if(group==NULL)
return;
cls=session->FindClass(group,"f_getrow");
if(cls==NULL)
return;
UsageThismethodsearchesforaPowerBuilderclasswiththegivennameinthegivengroup.Forexample,inawindowdefinitionw_1,w_1isagroup,andw_1andcontrolscontainedinitareallclassesofgroupw_1.
SeeAlso
FindGroup|NewObject
IPB_Sessioninterface:FindClassByClassIDmethod
DescriptionSearchesforaclasswithagivennameandagivenID.
SyntaxFindClass(pbgroupgroup,pbintclassID)
Argument Description
group Thehandleofthegroupinwhichtheclassresides
classID Theclassnameinlowercase
ReturnValuespbclassornullonfailure.
UsageThismethodsearchesforaPowerBuilderclasswiththegivennameandthegivenID.
SeeAlsoFindGroup|NewObject
IPB_Sessioninterface:FindGroupmethod
DescriptionSearchesforagroupwithagivennameandgrouptypeinthecurrentlibrarylist.
SyntaxFindGroup(LPCTSTRname,pbgroup_typetype)
Argument Description
name Thegroupnameinlowercase
type Anenumeratedtypedefinedinpbgroup_type
ReturnValuespbgroupornullonfailure.
ExamplesThisexamplefindsthegroupassociatedwithuser_exceptionandusesthegrouptofindtheclass:group=session->FindGroup("user_exception",
pbgroup_userobject);
if(group==NULL)
return;
cls=session->FindClass(group,"user_exception")
SeeAlsoFindClass|NewObject
IPB_Sessioninterface:FindMatchingFunctionmethod
DescriptionFindsafunctionthathasthespecifiedargumentlist.
SyntaxFindMatchingFunction(pbclasscls,LPCTSTRmethodName,PBRoutineType
Argument Description
cls pbclasscontainingthemethod.
methodName Thestringnameofthemethodinlowercase.
rt Typeofthemethod:PBRT_FUNCTIONforfunctionorPBRT_EVENTforevent.
readableSignature
Acomma-separatedstringlistingthetypesofthemethod'sarguments.Thereturntypeofthemethodisnotincludedinthestring.SeetheUsagesectionforexamples.
ReturnValuespbmethodID.
ExamplesThisexamplereturnsthemethodIDofafunctionnameduf_testthattakesanintegerandadoubleasarguments:pbclasscls;
pbmethodIDmid;
PBCallInfo*ci=newPBCallInfo;
unsignedlongret_val;
cls=Session->GetClass(myobj);
mid=Session->FindMatchingFunction(cls,"uf_test",
PBRT_FUNCTION,"int,double");
Session->InitCallInfo(cls,mid,ci);
UsageFindMatchingFunctionprovidesanalternativetotheGetMethodIDfunction.Itrequiresalistofthefunction'sarguments(thereadableSignature)insteadofthesignatureobtainedusingthepbsig125tool.ThistableshowsthereadableSignatureforeachofseveralfunctions.
Table7-3:FindMatchingFunctionreadablesignatureexamples
Functionprototype Signature
voidtest1() ""
inttest2() ""
stringtest3(inta,doubleb) "int,double"
datastoretest4(powerobjecta[],double
b[2to10,1to7])
"powerobject[],double[2
to10,1to7]"
inttest5(readonlyinta[10,20],ref
longc[])
"readonlyint[10,20],ref
long[])"
FindMatchingFunctiondoesnotchecktheaccesstypeofthefunction,soyoucanuseittoobtainthemethodIDofaprivatefunction.GetMethodIDcannotobtainthemethodIDofaprivatefunction.
SeeAlsoGetMethodID
IPB_Sessioninterface:FreeCallInfomethod
DescriptionFreesmemoryallocatedbyInitCallInfo.
SyntaxFreeCallInfo(PBCallInfo*ci)
Argument Description
ci ApointertothepreallocatedPBCallInfostructure
ReturnValuesNone.
ExamplesFreeCallInfoshouldbecalledwhenthePBCallInfostructureisnolongerneeded:Session->InvokeObjectFunction(myobj,mid,ci);
ret_val=ci.returnValue->GetInt();
Session->FreeCallInfo(ci);
deleteci;
returnret_val;
UsageThismethodfreesmemoryallocatedbyInitCallInfobutdoesnotfreethestructureciitself.
SeeAlsoInitCallInfo
IPB_Sessioninterface:Get<type>ArrayItemmethod
DescriptionObtainsthevalueofanarrayitemofaspecifiedtype.
SyntaxGetBlobArrayItem(pbarrayarray,pblongdim[],pbboolean&IsNull)
GetBoolArrayItem(pbarrayarray,pblongdim[],pbboolean&IsNull)
GetByteArrayItem(pbarrayarray,pblongdim[],pbboolean&IsNull)
GetCharArrayItem(pbarrayarray,pblongdim[],pbboolean&IsNull)
GetDateArrayItem(pbarrayarray,pblongdim[],pbboolean&IsNull)
GetDateTimeArrayItem(pbarrayarray,pblongdim[],pbboolean&IsNull
GetDecArrayItem(pbarrayarray,pblongdim[],pbboolean&IsNull)
GetDoubleArrayItem(pbarrayarray,pblongdim[],pbboolean&IsNull
GetIntArrayItem(pbarrayarray,pblongdim[],pbboolean&IsNull)
GetLongArrayItem(pbarrayarray,pblongdim[],pbboolean&IsNull)
GetLongLongArrayItem(pbarrayarray,pblonglongdim[],pbboolean&IsNull
GetObjectArrayItem(pbarrayarray,pblongdim[],pbboolean&IsNull
GetRealArrayItem(pbarrayarray,pblongdim[],pbboolean&IsNull)
GetStringArrayItem(pbarrayarray,pblongdim[],pbboolean&IsNull
GetTimeArrayItem(pbarrayarray,pblongdim[],pbboolean&IsNull)
GetUintArrayItem(pbarrayarray,pblongdim[],pbboolean&IsNull)
GetUlongArrayItem(pbarrayarray,pblongdim[],pbboolean&IsNull)
Argument Description
array Avalidpbarraystructure
dim Thedimensionofthearrayitemtobeobtained
IsNull Indicateswhetherthearrayitemisnull
ReturnValues
Thevalueofthearrayitem.
ExamplesThisexamplegetsthevalueofanarrayitemoftypepbobject:pbobjectpPBObject=NULL;
pbbooleanbIsNull=0;
pblongdim[1];
dim[0]=pbl+1;
pPBObject=session->GetObjectArrayItem(array,dim,
bIsNull);
SeeAlsoGetArrayInfo|GetArrayItemType|GetArrayLength|IsArrayItemNull|NewBoundedObjectArray|NewBoundedSimpleArray|NewUnboundedObjectArray|NewUnboundedSimpleArray|ReleaseArrayInfo|SetArrayItemToNull|SetArrayItemValue|Set<type>ArrayItem
IPB_Sessioninterface:Get<type>Fieldmethod
DescriptionAsetofmethodsthatgetsthevalueofaninstancefieldofanobject.
SyntaxGetArrayField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
GetBlobField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
GetBoolField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
GetByteField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
GetCharField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
GetDateField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
GetDateTimeField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
GetDecField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
GetDoubleField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
GetIntField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
GetLongField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
GetLongLongField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
GetObjectField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
GetRealField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
GetStringField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
GetTimeField(pbobjectobj,pbfieldIDfid,pbintvalue)
GetUintField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
GetUlongField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
Argument Description
obj Thehandleoftheobjectwhosefieldistobeaccessed
fid ThefieldIDofthespecifiedobject
isNull Indicateswhetherthefieldisnull
ReturnValuesApredefinedPBNIdatatypethatcorrespondstothePowerBuilderdatatypeinthemethodname.
ExamplesThisexamplegetsthevalueofafieldoftypepbstring:pbbooleanisNull;
pbstringpstr=
session->GetStringField(proxy,fid,isNull);
if(pstr!=NULL)
{
myclass=session->GetString(pstr);
//processmyclass
}
SeeAlsoGetFieldID|GetFieldType|GetNumOfFields|IsFieldArray|IsFieldNull|IsFieldObject|SetFieldToNull|Set<type>Field
IPB_Sessioninterface:Get<type>GlobalVarmethod
DescriptionAsetofmethodsthatgetsthevalueofaglobalvariableofaspecificdatatype.
SyntaxGetArrayGlobalVar(pbfieldIDfid,pbboolean&isNull)
GetBlobGlobalVar(pbfieldIDfid,pbboolean&isNull)
GetBoolGlobalVar(pbfieldIDfid,pbboolean&isNull)
GetByteGlobalVar(pbfieldIDfid,pbboolean&isNull)
GetCharGlobalVar(pbfieldIDfid,pbboolean&isNull)
GetDateGlobalVar(pbfieldIDfid,pbboolean&isNull)
GetDateTimeGlobalVar(pbfieldIDfid,pbboolean&isNull)
GetDecGlobalVar(pbfieldIDfid,pbboolean&isNull)
GetDoubleGlobalVar(pbfieldIDfid,pbboolean&isNull)
GetIntGlobalVar(pbfieldIDfid,pbboolean&isNull)
GetLongGlobalVar(pbfieldIDfid,pbboolean&isNull)
GetLongLongGlobalVar(pbfieldIDfid,pbboolean&isNull)
GetObjectGlobalVar(pbfieldIDfid,pbboolean&isNull)
GetRealGlobalVar(pbfieldIDfid,pbboolean&isNull)
GetStringGlobalVar(pbfieldIDfid,pbboolean&isNull)
GetTimeGlobalVar(pbfieldIDfid,pbintvalue)
GetUintGlobalVar(pbfieldIDfid,pbboolean&isNull)
GetUlongGlobalVar(pbfieldIDfid,pbboolean&isNull)
Argument Description
fid ThefieldIDoftheglobalvariable
isNull Indicateswhetherthevariableisnull
ReturnValues
ApredefinedPBNIdatatypethatcorrespondstothePowerBuilderdatatypeinthemethodname.
ExamplesThiscodegetsthevalueofaglobalvariableofdatatypelongusingitsfieldID:fid=session->GetGlobalVarID("l_gvar");
l_val=session->GetLongGlobalVar(fid,isNull);
session->SetLongGlobalVar(fid,l_val+1);
SeeAlsoGetGlobalVarID|GetGlobalVarType|IsGlobalVarArray|IsGlobalVarNull|IsGlobalVarObject|SetGlobalVarToNull|Set<type>GlobalVar
IPB_Sessioninterface:Get<type>SharedVarmethod
DescriptionAsetofmethodsthatgetsthevalueofasharedvariableofaspecificdatatype.
SyntaxGetArraySharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull)
GetBlobSharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull)
GetBoolSharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull)
GetByteSharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull)
GetCharSharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull)
GetDateSharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull)
GetDateTimeSharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull
GetDecSharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull)
GetDoubleSharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull
GetIntSharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull)
GetLongSharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull)
GetLongLongSharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull
GetObjectSharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull
GetRealSharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull)
GetStringSharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull
GetTimeSharedVar(pbgroupgroup,pbfieldIDfid,pbintvalue)
GetUintSharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull)
GetUlongSharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull)
Argument Description
group Thegroupwhosesharedvariableistobeaccessed
fid ThefieldIDofthesharedvariable
isNull Indicateswhetherthevariableisnull
ReturnValuesApredefinedPBNIdatatypethatcorrespondstothePowerBuilderdatatypeinthemethodname.
ExamplesThiscodegetsthevalueofasharedvariableoftypeinteger:curGroup=session->GetCurrGroup();
fid=session->GetSharedVarID(curGroup,"i_svar");
if(fid==0xffff)
{
MessageBox(NULL,"Illegalfid!","default",MB_OK);
return;
}
i_val=session->GetIntSharedVar(curGroup,fid,
isNull);
session->SetIntSharedVar(curGroup,fid,i_val+1);
SeeAlsoGetSharedVarID|GetSharedVarType|IsSharedVarArray|IsSharedVarNull|IsSharedVarObject|Set<type>SharedVar|SetSharedVarToNull
IPB_Sessioninterface:GetArrayInfomethod
DescriptionObtainsinformationaboutanarray.
SyntaxGetArrayInfo(pbarrayarray)
Argument Description
array Avalidarrayhandle
ReturnValuesPBArrayInfo*.
ExamplesThisIF-ELSEstatementpopulatesaPBArrayInfostructureifthearrayinthefirstvalueofaPBCallInfostructureisnotnull:if(!(ci->pArgs->GetAt(0)->IsNull()))
{
array=ci->pArgs->GetAt(0)->GetArray();
pArrayInfo=session->GetArrayInfo(array);
pArrayItemCount=session->GetArrayLength(array);
}
else
{
//NULLarray
pArrayItemCount=0;
}
UsageIfthearrayisanunboundedarray,theboundsinformationinPBArrayInfoisundetermined.ThereturnedPBArrayInfomustbefreedlaterbyReleaseArrayInfo.
SeeAlsoGet<type>ArrayItem|GetArrayItemType|GetArrayLength|IsArrayItemNull|NewBoundedObjectArray|NewBoundedSimpleArray|NewUnboundedObjectArray|NewUnboundedSimpleArray|ReleaseArrayInfo|SetArrayItemToNull|SetArrayItemValue|Set<type>ArrayItem
IPB_Sessioninterface:GetArrayItemTypemethod
DescriptionObtainsthedatatypeofaniteminanarray.
SyntaxGetArrayItemType(pbarrayarray,pblongdim[])
Argument Description
array Avalidpbarraystructure.
dimApblongarraytoholdtheindexesofeachdimensionofthearray.Thesizeofthearraymustequalthedimensionsofarray.
ReturnValuespbuint.
SeeAlsoGet<type>ArrayItem|GetArrayInfo|GetArrayLength|IsArrayItemNull|NewBoundedObjectArray|NewBoundedSimpleArray|NewUnboundedObjectArray|NewUnboundedSimpleArray|ReleaseArrayInfo|SetArrayItemToNull|SetArrayItemValue
|Set<type>ArrayItem
IPB_Sessioninterface:GetArrayLengthmethod
DescriptionObtainsthelengthofanarray.
SyntaxGetArrayLength(pbarrayarray)
Argument Description
array Avalidarrayhandle
ReturnValuespblong.
ExamplesThisIF-ELSEstatementpopulatesaPBArrayInfostructure.IfthearrayinthefirstvalueofaPBCallInfostructureisnotnull,itsetsthevalueofthepArrayItemCountvariabletothelengthofthearray:if(!(ci->pArgs->GetAt(0)->IsNull()))
{
array=ci->pArgs->GetAt(0)->GetArray();
pArrayInfo=session->GetArrayInfo(array);
pArrayItemCount=session->GetArrayLength(array);
}
else
{
//NULLarray
pArrayItemCount=0;
}
SeeAlsoGet<type>ArrayItem|GetArrayInfo|IsArrayItemNull
|NewBoundedObjectArray|NewBoundedSimpleArray|NewUnboundedObjectArray|NewUnboundedSimpleArray|ReleaseArrayInfo|SetArrayItemToNull|SetArrayItemValue|Set<type>ArrayItem
IPB_Sessioninterface:GetBlobmethod
DescriptionReturnsapointertothedatabufferforablob.
SyntaxGetBlob(pbblobbin)
Argument Description
bin Apointertothesourcebuffer
ReturnValuesvoid*.
ExamplesInthisCASEclause,thevaluereturnedfromGetBlobiscasttotheLPCTSTRvariablepStr.Ifitisnotnull,thereturnvalueinthePBCallInfostructureissettothevalueoftheblob:casepbvalue_blob:
pStr=(LPCTSTR)Session->GetBlob(retVal.blob_val);
if(strncmp(pStr,"null",4)==0)
ci->returnValue->SetToNull();
else
{
ci->returnValue->SetBlob(retVal.blob_val);
Session->ReleaseValue(retVal);
}
break;
SeeAlsoGetBlobLength|NewBlob|SetBlob
IPB_Sessioninterface:GetBlobLengthmethod
DescriptionReturnsthelengthinbytesofblobdatainabuffer.
SyntaxGetBlobLength(pbblobbin)
Argument Description
bin Apointertothesourcebuffer
ReturnValuespblong.
ExamplesInthisexample,theIPB_ValueGetBlobfunctionisusedtogetablobvaluefromthePBCallInfostructure.ThelengthoftheblobisusedasanargumenttotheNewBlobfunction:PBCallInfo*ci=newPBCallInfo;
pbblobret_val;
pblongbloblen;
ret_val=ci.returnValue->GetBlob();
bloblen=Session->GetBlobLength(ret_val);
ret_val=Session->NewBlob
(Session->GetBlob(ret_val),bloblen);
SeeAlsoGetBlob|NewBlob|SetBlob
IPB_Sessioninterface:GetClassmethod
DescriptionReturnstheclasshandleofaPowerBuilderobject.ThisfunctionismostfrequentlyusedtoobtainaclasshandleforusewiththeGetMethodIDfunction.
SyntaxGetClass(pbobjectobj)
Argument Description
obj AvalidPowerBuilderobjecthandle
ReturnValuespbclassornullonerror.
ExamplesInthisexample,GetClassisusedtoobtaintheclassofavariableoftypeUserDatasothattheclasscanbeusedasanargumenttotheGetMethodIDfunction:BOOLCALLBACKCFontEnumerator::EnumFontProc
(
LPLOGFONTlplf,
LPNEWTEXTMETRIClpntm,
DWORDFontType,
LPVOIDuserData
)
{
UserData*ud=(UserData*)userData;
pbclassclz=ud->session->GetClass(ud->object);
pbmethodIDmid=ud->session->GetMethodID
(clz,"onnewfont",PBRT_EVENT,"IS");
PBCallInfoci;
ud->session->InitCallInfo(clz,mid,&ci);
pbstringstr=ud->session->NewString
(lplf->lfFaceName);
ci.pArgs->GetAt(0)->SetPBString(str);
ud->session->TriggerEvent(ud->object,mid,&ci);
pbintret=ci.returnValue->GetInt();
ud->session->FreeCallInfo(&ci);
returnret==1?TRUE:FALSE;
}
SeeAlsoGetClassName|GetMethodID
IPB_Sessioninterface:GetClassNamemethod
DescriptionReturnsthenameofaclassinlowercase.
SyntaxGetClassName(pbclasscls)
Argument Description
cls Avalidclasshandle
ReturnValuesLPCTSTR.
ExamplesThisexamplegetsthenameofaclassandsetsthesizeofthevariablestLengthtothelengthofthereturnedstringplus1:LPCTSTRmyClassName=session->GetClassName(myClass);
size_tstLength=strlen((LPSTR)myClassName)+1;
UsageWhenyouhavefinishedusingthename,calltheReleaseStringmethodtofreethememoryacquired.
SeeAlsoGetClass|ReleaseString
IPB_Sessioninterface:GetCurrGroupmethod
DescriptionObtainsthenameofthecurrentgroup.
SyntaxGetCurrGroup()
ReturnValuespbgroupornullonfailure.
ExamplesThisexamplegetsthenameofthecurrentgroupandusesittoobtaintheidentifierofasharedvariable,getthesharedvariable'svalue,andresetthesharedvariable'svalue:curGroup=session->GetCurrGroup();
fid=session->GetSharedVarID(curGroup,"i_svar");
if(fid==0xffff)
{
MessageBox(NULL,"Illegalfid!","default",MB_OK);
return;
}
i_val=session->GetIntSharedVar(curGroup,fid,
isNull);
session->SetIntSharedVar(curGroup,fid,i_val+1);
SeeAlsoGet<type>SharedVar|GetSharedVarID|Set<type>SharedVar
IPB_Sessioninterface:GetDateStringmethod
DescriptionConvertsdatainapbdateobjecttoastring.
SyntaxGetDateString(pbdatedate)
Argument Description
date Thepbdatedataobjecttobeconvertedtoastring.
ReturnValuesLPCTSTR.
SeeAlsoNewDate|ReleaseDateString|SetDate
IPB_Sessioninterface:GetDateTimeStringmethod
DescriptionConvertsdatainapbdatetimeobjecttoastring.
SyntaxGetDateTimeString(pbdatetimedatetime)
Argument Description
datetime Thepbdatetimedataobjecttobeconvertedtoastring.
ReturnValuesLPCTSTR.
SeeAlsoNewDateTime|ReleaseDateTimeString|SetDateTime
IPB_Sessioninterface:GetDecimalStringmethod
DescriptionConvertsdecimaldatainapbdecobjecttoastring.
SyntaxGetDecimalString(pbdecdec)
Argument Description
dec Thepbdecdataobjecttobeconvertedtoastring.
ReturnValuesLPCTSTR.
ExamplesThiscodecheckswhetheravalueinthePBCallInfostructureisnull.Ifitisnot,itsetsthevalueinthepArgumentsarraytothevalueinPBCallInfo:casepbvalue_dec:
if(ci->pArgs->GetAt(i)->IsNull())
{
pArguments[i].dec_val=Session->NewDecimal();
Session->SetDecimal(pArguments[i].dec_val,"1.0");
}
else
pArguments[i].dec_val=
ci->pArgs->GetAt(i)->GetDecimalString();
break;
SeeAlsoNewDecimal|ReleaseDecimalString|SetDecimal
IPB_Sessioninterface:GetEnumItemNamemethod
DescriptionObtainsthenameofanenumeratedvariable.
SyntaxGetEnumItemName(LPCTSTRenumName,longenumItemValue)
ReturnValuesLPCTSTR.
UsageWhenyouhavefinishedusingthename,calltheReleaseStringmethodtofreethememoryacquired.
SeeAlsoGetEnumItemValue|ReleaseString
IPB_Sessioninterface:GetEnumItemValuemethod
DescriptionObtainsthevalueofanenumeratedvariable.
SyntaxGetEnumItemValue(LPCTSTRenumName,LPCTSTRenumItemName)
ReturnValuesLong.
ExamplesThisexamplegetsthenumericvaluefortheboolean!enumeratedvalue,thenusesittoreturnthestringvalue:pblonglType=session->GetEnumItemValue("object",
boolean");//returns138
LPCTSTRszEnum=session->GetEnumItemName("object",
lType);//returns"boolean"
UsageGetEnumItemValueandGetEnumItemNamesupportenumeratedtypes.Theyallowyoutoconvertthenameofanenumeratedvalue,astringwithanappendedexclamationmark(!),toanintegervalue,andviceversa.The!charactermustbeomitted
Whenyouusethesefunctions,theenumItemNameshouldnotusetheappendedexclamationmark(!)character.ToreturnanenumeratedvaluefromanextensiontoPowerScript,youmustusetheSetLongfunctiontosetthevalueoftheenumeratedvariableintoIPB_Value.UsingSetIntorSetShortfails.However,youcanuseGetIntorGetShortaswellasGetLongtoobtaintheenumeratedvariable'svalue,assumingthevalueisintheappropriaterange.Forexample,ifyouattempttouseGetInttoobtainavaluethatis
morethan32767,thereturnedvalueistruncated.
SeeAlsoGetEnumItemName
IPB_Sessioninterface:GetExceptionmethod
DescriptionObtainsthecurrentthrownexceptionobject.
SyntaxGetException()
ReturnValuespbobject.
ExamplesThiscodegetsthecurrentexceptionobject,clearstheexception,andgetstheclassoftheexceptionobject:pbclasscls;
pbobjectex;
...
ex=session->GetException();
session->ClearException();
cls=session->GetClass(ex);
SeeAlsoClearException|HasExceptionThrown
IPB_Sessioninterface:GetFieldIDmethod
DescriptionObtainstheinternalIDofaclassinstancevariable.
SyntaxGetFieldID(pbclasscls,LPCTSTRfieldName)
Argument Description
cls Theclassinwhichthefieldresides
fieldName Theinstancemembername,inlowercase
ReturnValuespbfieldIDor0xffffifafieldIDcannotbefound.
ExamplesThisfunctionobtainstheidentifierofaclass'svisiblefield,ifitexists,andusesittosetthevalueofthefield:voidCallBack::f_setvisible(IPB_Session*session,
pbobjectdwobj)
{
pbclasscls;
IPB_Value*pv;
pbfieldIDfid;
pbstringstrtmp;
boolisTrue;
pbbooleanisNull;
cls=session->GetClass(dwobj);
fid=session->GetFieldID(cls,"visible");
if(fid==kUndefinedFieldID)
return;
isTrue=session->GetBoolField(dwobj,fid,isNull);
if(isTrue)
session->SetBoolField(dwobj,fid,false);
else
session->SetBoolField(dwobj,fid,true);
return;
}
UsageGetFieldIDisoneofasetoffunctionsthatallowsnativecodetoaccessthefieldsofJavaobjectsandgetandsettheirvalues.YouuseGetFieldIDtoretrievethevalueofafield,specifyingtheclassnameandthefieldname.ThefieldIDreturnedcanbeusedasanargumenttotherelatedfunctions.
SeeAlsoGetFieldType|Get<type>Field|GetNumOfFields|IsFieldArray|IsFieldNull|IsFieldObject|Set<type>Field|SetFieldToNull
IPB_Sessioninterface:GetFieldNamemethod
DescriptionObtainsthenameofthespecifiedfield.
SyntaxGetFieldName(pbclasscls,pbfieldIDfid)
Argument Description
cls Theclassthatdefinesthefield
fid TheinternalIDoftheclassinstancevariable
ReturnValuesLPCTSTR.Thefieldnameofthespecifiedfield.IfanincorrectfieldIDisspecified,thisfunctionreturnsnull.
UsageWhenyouhavefinishedusingthename,calltheReleaseStringmethodtofreethememoryacquired.
SeeAlsoGetFieldID|ReleaseString
IPB_Sessioninterface:GetFieldTypemethod
DescriptionObtainsthedatatypeofafielddeclaredbyaclass.
SyntaxGetFieldType(pbclasscls,pbfieldIDfid)
Argument Description
cls Theclassthatdefinesthefield
fid TheinternalIDoftheclassinstancevariable
ReturnValuespbint.Asimpledatatypedefinedinthelistofpbvalue_typeenumeratedtypes,suchaspbvalue_int.See"PBNIenumeratedtypes".
ExamplesThisstatementgetsthetypeofthespecifiedfieldID:pbintpbfieldType=session->GetFieldType(cls,fid);
SeeAlsoGetFieldID|Get<type>Field|GetNumOfFields|IsFieldArray|IsFieldNull|IsFieldObject|Set<type>Field|SetFieldToNull
IPB_Sessioninterface:GetGlobalVarIDmethod
DescriptionReturnstheinternalIDofaglobalvariable.
SyntaxGetGlobalVarID(LPCTSTRname)
Argument Description
name Thenameoftheglobalvariableinlowercase
ReturnValuespbfieldIDornullonfailure.
ExamplesThisexamplegetstheinternalidentifierofalongvariableandusesittogetandsetaglobalvariable:fid=session->GetGlobalVarID("l_gvar");
l_val=session->GetLongGlobalVar(fid,isNull);
session->SetLongGlobalVar(fid,l_val+1);
SeeAlsoGetGlobalVarType|Get<type>GlobalVar|IsGlobalVarArray|IsGlobalVarNull|IsGlobalVarObject|SetGlobalVarToNull|Set<type>GlobalVar
IPB_Sessioninterface:GetGlobalVarTypemethod
DescriptionObtainsthedatatypeofaglobalvariable.
SyntaxGetGlobalVarType(pbfieldIDfid)
Argument Description
fid TheinternalIDoftheclassinstancevariable
ReturnValuespbuint.Asimpledatatypedefinedinthelistofpbvalue_typeenumeratedtypes.
ExamplesThiscodetestsgettingandsettingaglobalintegervariableusingthefieldIDfid:fid=session->GetGlobalVarID("i_gvar");
if(session->GetGlobalVarType(fid)==pbvalue_int)
{
i_val=session->GetIntGlobalVar(fid,isNull);
session->SetIntGlobalVar(fid,i_val+1);
}
SeeAlsoGetGlobalVarID|Get<type>GlobalVar|IsGlobalVarArray|IsGlobalVarNull|IsGlobalVarObject|SetGlobalVarToNull
|Set<type>GlobalVar
IPB_Sessioninterface:GetMarshalermethod
DescriptionObtainsthemarshalerobjectassociatedwithaproxyobject.
SyntaxGetMarshaler(pbproxyObjectobj)
Argument Description
obj AnobjectoftypepbproxyObjectforwhichyouwanttofindthemarshaler.
ReturnValuesIPBX_Marshaler*.
ExamplesThiscodecreatesaJavamarshalerobjectandassociatesitwithaproxy.Later,GetMarshalerisusedtogetthemarshalerobject://CreateJavaMarshaler
JavaMarshaler*marshaler=newJavaMarshaler(env,
proxy,jobj);
//AssociatetheJavaMarshalerwiththe
//PowerBuilderproxy
session->SetMarshaler(proxy,marshaler);
ci->pArgs->GetAt(0)->SetObject(proxy);
ci->returnValue->SetLong(kSuccessful);
returnPBX_OK;
...
//Getthemarshaler
IPBX_Marshaler*pIPBX_Marshaler=NULL;
pIPBX_Marshaler=(IPBX_Marshaler*)session
->GetMarshaler(proxy);
SeeAlsoSetMarshaler
IPB_Sessioninterface:GetMethodIDmethod
DescriptionReturnstheIDoftherequestedmethod.
SyntaxGetMethodID(pbclasscls,LPCTSTRmethodName,PBRoutineTypert,LPCTSTR
Argument Description
cls pbclasscontainingthefunction.
methodNameThestringnameofthemethodinlowercase.
rt Typeofthemethod:PBRT_FUNCTIONforfunctionorPBRT_EVENTforevent.
signature
InternalsignatureofthePowerBuilderfunction,usedtoidentifypolymorphicmethodsinoneclass.Obtainedwiththepbsig125tool.Ifthesignatureisanullstring(""),thefirstmethodfoundwiththenamemethodNameisreturned.
publicOnlyAbooleanthatdetermineswhetheronlypublicmethodsaresearched(true)orallmethodsaresearched(false).Thedefaultistrue.
ReturnValuespbMethodIDofthemethodorkUndefinedMethodIDonerror.
ExamplesThisfunctionusesGetMethodIDtoobtaintheidentifier(mid)oftheonnewfontfunctionsothattheidentifiercanbeusedtoinitializethePBCallInfostructureandcallthefunction:BOOLCALLBACKCFontEnumerator::EnumFontProc
(
LPLOGFONTlplf,
LPNEWTEXTMETRIClpntm,
DWORDFontType,
LPVOIDuserData
)
{
UserData*ud=(UserData*)userData;
pbclassclz=ud->session->GetClass(ud->object);
pbmethodIDmid=ud->session->GetMethodID(clz,
"onnewfont",PBRT_EVENT,"IS");
PBCallInfoci;
ud->session->InitCallInfo(clz,mid,&ci);
pbstringstr=ud->session->
NewString(lplf->lfFaceName);
ci.pArgs->GetAt(0)->SetPBString(str);
ud->session->TriggerEvent(ud->object,mid,&ci);
pbintret=ci.returnValue->GetInt();
ud->session->FreeCallInfo(&ci);
returnret==1?TRUE:FALSE;
}
UsageTheGetMethodIDfunctionisusedtoobtaintheIDofamethodsoyoucanuseittoinvokefunctionsandtriggerevents.
SeeAlsoFindMatchingFunction|InvokeObjectFunction|TriggerEvent|"CallingPowerScriptfromanextension"
IPB_Sessioninterface:GetMethodIDByEventIDmethod
DescriptionReturnstheIDofthemethodthathasagivenpredefinedPowerBuildereventID.
SyntaxGetMethodIDByEventID(pbclasscls,LPCTSTReventID)
Argument Description
cls pbclasscontainingthemethod
eventID APowerBuilderpredefinedeventstring,suchaspbm_bnclicked
ReturnValuespbMethodIDofthemethodorkUndefinedMethodIDonerror.
ExamplesThisstatementobtainstheIDoftheeventidentifiedbythenamepbm_lbuttonup:pbmethodIDmid=d_session->GetMethodIDByEventID(clz,
"pbm_lbuttonup");
SeeAlsoGetMethodID
IPB_Sessioninterface:GetNativeInterfacemethod
DescriptionObtainsapointertotheinterfaceofanativeclass.
SyntaxGetNativeInterface(pbobjectobj)
Argument Description
obj Avalidobjecthandle
ReturnValuesIPBX_UserObject.
ExamplesThisexampleinvokesthefunctionf_retrieveinthenativeclassCmy_pbnitoretrieveaDataWindowobject:longf_retrieve(IPB_Session*session,pbintiarg,
pbobjectdwObj,pbobjectextObj)
{
Imy_pbni*pImy_pbni=NULL;
pblonglRet;
if(session->IsNativeObject(extObj))
{
pImy_pbni=(Imy_pbni*)session->
GetNativeInterface(extObj);
lRet=pImy_pbni->f_Retrieve(session,
iarg,dwObj);
}
returnlRet;
}
UsageUsethismethodinconjunctionwithIsNativeObjecttoobtainadirect
referencetotheIPBX_UserObjectassociatedwithanativeclassinthesamePowerBuilderextension.Theclassanditsmethodscanthenbeaccesseddirectly.
SeeAlsoIsNativeObject
IPB_Sessioninterface:GetNumOfFieldsmethod
DescriptionReturnsthenumberoffieldsinthespecifiedclass.
SyntaxGetNumOfFields(pbclasscls)
Argument Description
cls Avalidclasshandlefortheclasswhosefieldistobeaccessed
ReturnValuespbulong.
ExamplesThiscodegetsthenumbersoffieldsintheclassclz:pbclassclz=d_session->GetClass(d_pbobj);
pbulongnf=d_session->GetNumOfFields(clz);
SeeAlsoGetFieldID|Get<type>Field|IsFieldArray|IsFieldNull|IsFieldObject|SetFieldToNull|Set<type>Field
IPB_Sessioninterface:GetPBAnyArrayItemmethod
DescriptionObtainsthevalueofaglobalvariableoftypeAny.
SyntaxGetPBAnyArrayItem(pbarrayarray,pblongdim[],pbboolean&isNull)
Argument Description
array Avalidpbarraystructure.
dimApblongarraytoholdtheindexesofeachdimensionofthearray.Thesizeofthearraymustequalthedimensionsofarray.
isNull Indicateswhetherthevariableisnull
ReturnValuesIPB_Value*.
UsageSeeGetPBAnyField.
SeeAlsoGetPBAnyField|GetPBAnyGlobalVar|GetPBAnySharedVar
IPB_Sessioninterface:GetPBAnyFieldmethod
DescriptionObtainsthevalueofavariableoftypeAny.
SyntaxGetPBAnyField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
Argument Description
obj Avalidobjecthandlefortheobjectwhosevalueistobeobtained
fid ThefieldIDofthevariable
isNull Indicateswhetherthevariableisnull
ReturnValuesIPB_Value*.
ExamplesThisexampletestsallthefunctionsusedtogetthevalueofvariablesoftypeAny,usingPushLocalFrameandPopLocalFrametosimulatethescopeofafunctioncall:session->PushLocalFrame();
pbgroupvgroup=session->FindGroup("n_test",
pbgroup_userobject);
pbclassvcls=session->FindClass(vgroup,"n_test");
pbobjectvobj=session->NewObject(vcls);
pbbooleanisNull;
pbfieldIDvfid=session->GetFieldID(vcls,"i_a");
IPB_Value*value=session->GetPBAnyField(vobj,
vfid,isNull);
pbstringstr=value->GetString();//saveactualvalue
vfid=session->GetSharedVarID(vgroup,"s_a");
value=session->GetPBAnySharedVar(vgroup,
vfid,isNull);
//Gettheactualvaluehere.
vfid=session->GetGlobalVarID("g_a");
value=session->GetPBAnyGlobalVar(vfid,isNull);
//Gettheactualvaluehere.
vfid=session->GetFieldID(vcls,"i_array");
pbarrayarr=session->GetArrayField(vobj,
vfid,isNull);//Gettheanyarrayfirst.
longdim=1;
value=session->GetPBAnyArrayItem(arr,&dim,isNull);
//Gettheactualvaluehere.
session->PopLocalFrame();
UsageThevalueyouretrievemustbeofdatatypeAnytousethisfunction;thatis,thevariableassociatedwiththefunctionmustbedeclaredasavariableoftypeAnyinthedevelopmentenvironment.Ifitisnot,thefunctionreturnsanullpointerandthevalueofisNullissettotrue.ThisfunctionreturnsapointertoanIPB_Valueinstance.Whenitiscalled,memoryisallocatedforthereturnedIPB_Valueinstance,andthepointerisrecordedinthecurrentlocalframe.Thepointerisdeletedautomaticallywhenthecurrentlocalframeispopped,whichoccurswhenthecurrentlocalfunctionreturns(youcanalsocallPopLocalFrametoforcetheframetobepopped).Ifyouwanttousethevaluereturned,youmustsavethevaluepointedtobytheIPB_Valueinstance(nottheIPB_Valueinstanceitself)beforetheframeispopped.Ifyousavethepointeritself,thevalueisonlyvaliduntiltheoriginalvalueisdestroyed.YoucanusetheAcquireValuefunctiontosavethevalue,oroneoftheIPB_ValueGet<type>functions.Forexample,thefollowingcodesavesthestringvalueintheIPB_Valueinstanceivalueintothestringstr.Thevalueinstrcanbeusedafterthelocalframeispoppedandivalueisdeleted:IPB_Value*ivalue=session->GetPBAnyField(vobj,vfid,
isNull);
pbstringstr=ivalue->GetString();
IfyoudonotknowtheactualdatatypeoftheAnyvariable,usethe
IPB_ValueGetTypefunctiontogetitsdatatypefirst,thenusetheappropriategetfunctiontogetitsvalue.IPB_Valueholdsareferencetotheoriginalvalue
ThevalueintheIPB_Valueinstanceisareferencetotheoriginalvalue.IfyouchangetheactualvalueofthereturnedIPB_Value,theoriginalvalueisalsochanged.IfyouusetheAcquireValuefunctiontosavethevalue,itclonesanewIPB_ValueandresetstheexistingIPB_Valuepointer.
SeeAlsoGetPBAnyArrayItem|GetPBAnyGlobalVar|GetPBAnySharedVar
IPB_Sessioninterface:GetPBAnyGlobalVarmethod
DescriptionObtainsthevalueofaglobalvariableoftypeAny.
SyntaxGetPBAnyGlobalVar(pbfieldIDfid,pbboolean&isNull)
Argument Description
fid ThefieldIDofthevariable
isNull Indicateswhetherthevariableisnull
ReturnValuesIPB_Value*.
UsageSeeGetPBAnyField.
SeeAlsoGetPBAnyArrayItem|GetPBAnyField|GetPBAnySharedVar
IPB_Sessioninterface:GetPBAnySharedVarmethod
DescriptionObtainsthevalueofasharedvariableoftypeAny.
SyntaxGetPBAnySharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull)
Argument Description
group Thegrouptowhichthevariablebelongs
fid ThefieldIDofthevariable
isNull Indicateswhetherthevariableisnull
ReturnValuesIPB_Value*.
UsageSeeGetPBAnyField.
SeeAlsoGetPBAnyArrayItem|GetPBAnyField|GetPBAnyGlobalVar
IPB_Sessioninterface:GetPropmethod
DescriptionRetrievesapointertothedatavalueofavariablethathasbeenregisteredasasharedpropertyforthecurrentIPBsession.
SyntaxGetProp(LPCTSTRname)
Argument Description
name Thenameofthevariablewhosevalueistoberetrieved.
ReturnValuesVoid*.Ifthevariabledoesnotexist,returnsnull.
ExamplesSeeSetProp.
UsageThevariable'snamemustfirstberegisteredwiththesessionusingtheSetPropfunction.
SeeAlsoRemoveProp|SetProp
IPB_Sessioninterface:GetResultSetAccessormethod
DescriptionObtainsaninterfacethroughwhichyoucanreaddatafromaresultset.
SyntaxGetResultSetAccessor(pbobjectrs)
Argument Description
rs ApbobjectholdingaresultsetobtainedusingCreateResultSet
ReturnValuesIPB_ResultSetAccessor
ExamplesThisexamplegetsaresultset,rs,fromthereturnvalueofaPowerScriptfunctionandusesittocreateanIPB_ResultSetAccessorobject,rsa:pbobjectrs=ci.returnValue->GetObject();
IPB_ResultSetAccessor*rsa=
session->GetResultSetAccessor(rs);
SeeAlsoCreateResultSet|ReleaseResultSetAccessor
IPB_Sessioninterface:GetSharedVarIDmethod
DescriptionReturnstheinternalIDofasharedvariable.
SyntaxGettSharedVarID(pbgroupgroup,LPCTSTRfieldname)
Argument Description
group Thegrouptowhichthesharedvariablebelongs
fieldname Thenameofthefieldthatcontainsthesharedvariable,inlowercase
ReturnValuespbfieldID.Returns0xffffiftheIDcannotbefound.
ExamplesThiscodeusesGetSharedVarIDtoobtainthefieldIDofasharedvariable,thenusesthatIDtoobtainthevalueofthevariable:curGroup=session->GetCurrGroup();
fid=session->GetSharedVarID(curGroup,"i_svar");
if(fid==0xffff)
{
MessageBox(NULL,"Illegalfid!","default",MB_OK);
return;
}
i_val=session->GetIntSharedVar(curGroup,fid,
isNull);
SeeAlsoGet<type>SharedVar|GetSharedVarType|IsSharedVarArray
|IsSharedVarNull|IsSharedVarObject|Set<type>SharedVar|SetSharedVarToNull
IPB_Sessioninterface:GetSharedVarTypemethod
DescriptionObtainsthedatatypeofthespecifiedsharedvariable.
SyntaxGetSharedVarType(pbgroupgroup,pbfieldIDfid)
Argument Description
group Thegrouptowhichthesharedvariablebelongs
fid TheinternalfieldIDofthesharedvariable
ReturnValuespbuint.Asimpledatatypedefinedinthelistofpbvalue_typeenumeratedtypes.
ExamplesThisexamplegetsthefieldIDofasharedvariable,thenusesthatIDtogetthetypeofthesharedvariable:pbuintpbvaltype;
curGroup=session->GetCurrGroup();
fid=session->GetSharedVarID(curGroup,"i_svar");
pbvaltype=session->GetSharedVarType(curGroup,fid);
SeeAlsoGet<type>SharedVar|GetSharedVarID|IsSharedVarArray|IsSharedVarNull|IsSharedVarObject
|Set<type>SharedVar|SetSharedVarToNull
IPB_Sessioninterface:GetStringmethod
DescriptionReturnsapointertothestringpassedinasanargument.
SyntaxGetString(pbstring*string)
Argument Description
string Apointertoapbstring
ReturnValuesLPCTSTR.
ExamplesThisexampleusestheIPB_ValueGetStringfunctiontoobtainastringvaluefromthePBCallInfostructure.Ifthestringisnotnull,theIPB_SessionGetStringfunctionsetsthevalueoftheproxynamestringtoapointertothereturnedvalue:stringproxyName;
{
pbstringpn=ci->pArgs->GetAt(2)->GetString();
if(pn==NULL)
{
ci->returnValue->SetLong(kInvalidProxyName);
returnPBX_OK;
}
else
{
proxyName=session->GetString(pn);
}
}
Usage
Whenyouhavefinishedusingthestring,calltheReleaseStringmethodtofreethememoryacquired.
SeeAlsoGetStringLength|NewString|ReleaseString|SetString
IPB_Sessioninterface:GetStringLengthmethod
DescriptionReturnsthelengthofastringinbyteswithouttheterminator.
SyntaxGetStringLength(pbstringstring)
Argument Description
string Thepbstringwhoselengthistobedetermined
ReturnValuespblong.
ExamplesThesestatementssetthevalueofapblongvariabletothelengthofastring:pblonglong_val;
pbstringstr_val;
long_val=session->GetStringLength(str_val);
SeeAlsoGetString|NewString|SetString
IPB_Sessioninterface:GetSuperClassmethod
DescriptionReturnstheancestorclassofthespecifiedclass,ifany.
SyntaxGetSuperClass(pbclasscls)
Argument Description
cls Avalidclasshandleforthedescendentclass
ReturnValuespbclassor0iftheclasshasnoancestor.
ExamplesThesestatementsgettheclassofanobjectinthePBCallInfostructure,theancestorclassofthatclass,andthenthenameoftheancestorclass:pbclasscls,cls_parent;
LPCSTRclsname;
cls=Session->GetClass(ci->pArgs->GetAt(0)->
GetObject());
cls_parent=Session->GetSuperClass(cls);
clsname=Session->GetClassName(cls_parent);
SeeAlsoGetClass|GetClassName
IPB_Sessioninterface:GetSystemClassmethod
DescriptionReturnsthefirstsystemclassthattheinputclassinheritsfrom.
SyntaxGetSystemClass(pbclasscls)
Argument Description
cls Adescendentclasswhoseancestorsystemclassistobedetermined
ReturnValuespbclassornullonerror.
SeeAlsoGetMethodID|GetSystemGroup
IPB_Sessioninterface:GetSystemGroupmethod
DescriptionReturnsaPowerBuilderinternalsystemgroup.
SyntaxGetSystemGroup()
ReturnValuespbclassornullonerror.
UsageGetSystemGroupreturnsthePowerBuilderinternalsystemgroup,whichcontainsallthesystemtypessuchasPowerObject,NonVisualObject,Structure,Window,CommandButton,andsoon.Youcanusethissystemgrouptoobtainasystemclass.YoumightneedtocallPowerScriptfunctionsinthePowerBuilderextension.Toachievethis,youfirstneedtogetthepbclassthatthePowerScriptfunctionclassresidesin.ThiscodegetsthePowerBuildersystemfunctionclass:pbgroupsysGroup=session->GetSystemGroup();
pbclasssysFuncClass=session->FindClass(sysGroup,
"SystemFunctions");
Afteryougetthesystemclass,youcanobtainthemethodIDofaPowerScriptfunctionbycallingFindMatchingFunction,andthenyoucaninvokethePowerScriptfunction.
SeeAlsoFindMatchingFunction|GetSystemClass
IPB_Sessioninterface:GetTimeStringmethod
DescriptionConvertsdatainapbtimeobjecttoastring.
SyntaxGetTimeString(pbtimetime)
Argument Description
time Thepbtimedataobjecttobeconvertedtoastring.
ReturnValuesLPCTSTR.
SeeAlsoNewString|ReleaseTimeString|SetString
IPB_Sessioninterface:HasExceptionThrownmethod
DescriptionChecksfortheexistenceofanexceptionthathasbeenthrownbutnotcleared.
SyntaxHasExceptionThrown()
ReturnValuespbboolean.ReturnstrueifaPowerBuilderexceptionhasbeenthrownbutnotcleared.
ExamplesThisexampletestswhetheranexceptionhasbeenthrownsoitcanbehandledandcleared:try
{
session->InvokeObjectFunction(pbobj,mid,&ci);
//WasPBexceptionthrown?
if(session->HasExceptionThrown())
{
//HandlePBexception
session->ClearException();
}
}
SeeAlsoClearException|GetException|ThrowException
IPB_Sessioninterface:HasPBVisualObjectmethod
DescriptionDetermineswhetheranyPowerBuilderwindows,visibleorhidden,arestillinexistence.
SyntaxHasPBVisualObject()
ReturnValuespbboolean.ReturnstrueifanyPowerBuilderwindowsarestillalive.Ifanywindowsthatarenotresponsewindowsarestillalive,thePowerBuilderapplicationreturnsimmediatelyunlessyoumanuallyaddamessageloop.
ExamplesThisexampleissimilartotheexampleforRestartRequested,butitincludesacalltoHasPBVisualObjectthatopensamessageloopifthereturnvalueistrue:PBXRESULTPB_MyWinAppRunner::RunApplication()
{
PBXRESULTres;
pbbooleanrestart=FALSE;
do
{
res=StartApplication();
if(res==PBX_OK)
//Processmessagedispatch
{
if(GetSession()->HasPBVisualObject())
{
MSGmsg;
while(GetMessage(&msg,0,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if(!GetSession()->HasPBVisualObject())
break;
}
}
}
else
break;
restart=GetSession()->RestartRequested();
if(restart)
RecreateSession();
}while(restart);
returnCleanApplication();
}
UsageRestartRequestedandHasVisualPBObjectareusedintheimplementationoftheIPB_VMRunApplicationfunction.YounolongerneedtouseanexternalmessagelooptocheckforWindowsmessageswhenyoucalltheRunApplicationfunctionasyoudidinversionsofPBNIpriortoPowerBuilder10.5.
SeeAlsoRestartRequested|RunApplication
IPB_Sessioninterface:InitCallInfomethod
DescriptionInitializesthePBCallInfostructure.
SyntaxInitCallInfo(pbclasscls,pbmethodIDmid,PBCallInfo*ci)
Argument Description
cls Thepbclasscontainingthemethod
mid ThepbMethodIDreturnedbyGetMethodID
ci ApointertoapreallocatedPBCallInfostructure
ReturnValuesPBXRESULT.ReturnsPBX_OKonsuccess,andPBX_E_INVALID_ARGUMENTonfailure.
ExamplesThisexampleshowstheimplementationofaTriggerEventfunctioninavisualclass.Ittakesaneventnameasanargument,obtainstheclassandmethodIDneededtoinitializethePBCallInfostructure,triggerstheevent,andfreesthePBCallInfostructure:voidCVisualExt::TriggerEvent(LPCTSTReventName)
{
pbclassclz=d_session->GetClass(d_pbobj);
pbmethodIDmid=d_session->GetMethodID(clz,
eventName,PBRT_EVENT,"I");
PBCallInfoci;
d_session->InitCallInfo(clz,mid,&ci);
d_session->TriggerEvent(d_pbobj,mid,&ci);
d_session->FreeCallInfo(&ci);
}
UsageOnreturn,thismethodallocatesenoughspaceforthearguments,andtheninitializestheargumentsandreturnvalue.YoumustsetappropriatevaluesinthePBCallInfostructure.Notethatthestructureitselfmusthavebeenallocatedbeforethecall.
SeeAlsoFreeCallInfo
IPB_Sessioninterface:InvokeClassFunctionmethod
DescriptionInvokessystemoruserglobalfunctions.
SyntaxInvokeClassFunction(pbclasscls,pbmethodIDmid,PBCallInfo*ci)
Argument Description
cls
Theclassthatcontainstheglobalfunction.Ifthisisasystemfunction,clsisobtainedwithGetSystemFunctionsClass;otherwise,itisobtainedwithFindGroupandFindClass,withthefunctionnameasthegroup/classname.
mid ThepbMethodIDreturnedbyGetMethodID.
ci ApointertoapreallocatedPBCallInfostructure.
ReturnValuesPBXRESULT.ReturnsPBX_OKforsuccess,oroneofthefollowingforfailure:
PBX_E_INVALID_ARGUMENTPBX_E_INVOKE_METHOD_INACCESSABLEPBX_E_INVOKE_WRONG_NUM_ARGSPBX_E_INVOKE_REFARG_ERRORPBX_E_INVOKE_METHOD_AMBIGUOUSPBX_E_INVOKE_FAILUREPBX_E_INVOKE_FAILURE
ExamplesThisexamplegetsthePowerBuildersystemclassandusesittoinvoke
thedoublefunction:cls=session->GetSystemClass();
mid=session->GetMethodID
(cls,"double",PBRT_FUNCTION,"DA");
session->InitCallInfo(cls,mid,ci);
ci->pArgs->GetAt(0)->SetPBString(mystr);
session->InvokeClassFunction(cls,mid,ci);
UsageOnreturn,thismethodallocatesenoughspacesforthearguments,andtheninitializesargumentsandreturnvalue.YoumustsetappropriatevaluesinthePBCallInfostructure.Notethatthestructureitselfmusthavebeenallocatedbeforethecall.
SeeAlsoInvokeObjectFunction
IPB_Sessioninterface:InvokeObjectFunctionmethod
DescriptionInvokesaclassmembermethod.
SyntaxInvokeObjectFunction(pbobjectobj,pbmethodIDmid,PBCallInfo*ci)
Argument Description
obj Thepbobjectcontainingthemethod
mid ThepbMethodIDreturnedbyGetMethodID
ci ApointertoapreallocatedPBCallInfostructure
ReturnValuesPBXRESULT.ReturnsPBX_OKforsuccess,oroneofthefollowingforfailure:
PBX_E_INVALID_ARGUMENTPBX_E_INVOKE_METHOD_INACCESSABLEPBX_E_INVOKE_WRONG_NUM_ARGSPBX_E_INVOKE_REFARG_ERRORPBX_E_INVOKE_METHOD_AMBIGUOUSPBX_E_INVOKE_FAILUREPBX_E_INVOKE_FAILURE
ExamplesThiscodeinvokestheDataWindowUpdatefunctionandreturnsitsintegerreturnvalue:pbclasscls;
pbmethodIDmid;
PBCallInfo*ci=newPBCallInfo;
pbintret_val;
cls=session->GetClass(dwobj);
mid=session->GetMethodID
(cls,"Update",PBRT_FUNCTION,"I");
session->InitCallInfo(cls,mid,ci);
session->InvokeObjectFunction(dwobj,mid,ci);
ret_val=ci.returnValue->GetInt();
session->FreeCallInfo(ci);
deleteci;
returnret_val;
SeeAlsoInvokeClassFunction
IPB_Sessioninterface:IsArrayItemNullmethod
DescriptionReturnstrueifthearrayitemcontainsanullvalue;otherwiseitreturnsfalse.
SyntaxIsArrayItemNull(pbarrayarray,pblongdim[])
Argument Description
array Avalidpbarraystructurethatyouwanttocheckforanull-valuedarrayitem.
dimApblongarraytoholdtheindexesofeachdimensionofthearray.Thesizeofthearraymustequalthedimensionsofarray.
ReturnValuespbboolean.
SeeAlsoGetArrayItemType|Set<type>ArrayItem|SetArrayItemToNull
IPB_Sessioninterface:IsAutoInstantiatemethod
DescriptionReturnstrueifthespecifiedclassisanautoinstantiatedclass;otherwiseitreturnsfalse.
SyntaxIsAutoInstantiate(pbclass)
Argument Description
cls Avalidclasshandleorstructure
ReturnValuespbboolean.
IPB_Sessioninterface:IsFieldArraymethod
DescriptionReturnstrueifthefieldofthespecifiedobjectisanarray;otherwiseitreturnsfalse.
SyntaxIsFieldArray(pbclasscls,pbfieldfid)
Argument Description
cls Avalidclasshandlefortheclasswhosefieldistobeaccessed
fid ThefieldIDofthespecifiedobject
ReturnValuespbboolean.
ExamplesThiscodetestswhetherthefieldidentifiedbyfidisanarray,andifso,getsthearrayvalue:fid=session->GetFieldID(cls,"arr_val");
if(session->IsFieldArray(cls,fid))
{
arr_val=session->GetArrayField(myobj,fid,isNull);...
SeeAlsoGetFieldID|GetFieldType|Get<type>Field|GetNumOfFields|IsFieldNull
|IsFieldObject|SetFieldToNull|Set<type>Field
IPB_Sessioninterface:IsFieldNullmethod
DescriptionReturnstrueifthefieldofthespecifiedobjectisanullvalue;otherwiseitreturnsfalse.
SyntaxIsFieldNull(pbobjectobj,pbfieldfid)
Argument Description
obj Avalidobjecthandlefortheobjectwhosefieldistobeaccessed
fid ThefieldIDofthespecifiedobject
ReturnValuespbboolean.
ExamplesThesestatementstestwhetherthefieldidentifiedbyfidisnull:fid=session->GetFieldID(cls,"i_val");
if(session->IsFieldNull(myobj,fid))
SeeAlsoGetFieldID|GetFieldType|Get<type>Field|GetNumOfFields|IsFieldArray|IsFieldObject|SetFieldToNull
|Set<type>Field
IPB_Sessioninterface:IsFieldObjectmethod
DescriptionReturnstrueifthefieldofthespecifiedobjectisanobject;otherwiseitreturnsfalse.
SyntaxIsFieldObject(pbclasscls,pbfieldfid)
Argument Description
cls Avalidclasshandlefortheclasswhosefieldistobeaccessed
fid ThefieldIDofthespecifiedobject
ReturnValuespbboolean.
ExamplesThesestatementstestwhetherthefieldidentifiedbyfidisanobject:fid=session->GetFieldID(cls,"obj_val");
if(session->IsFieldObject(myobj,fid))
SeeAlsoGetFieldID|GetFieldType|Get<type>Field|GetNumOfFields|IsFieldArray|IsFieldNull|SetFieldToNull
|Set<type>Field
IPB_Sessioninterface:IsGlobalVarArraymethod
DescriptionReturnstrueiftheglobalvariablecontainsanarray;otherwiseitreturnsfalse.
SyntaxIsGlobalVarArray(pbfieldfid)
Argument Description
fid ThefieldIDoftheglobalvariable
ReturnValuespbboolean.
ExamplesThesestatementstestwhetherthefieldidentifiedbyfidisaglobalvariablearray:fid=session->GetGlobalVarID("arr_gvar");
if(session->IsGlobalVarArray(fid))
{
arr_val=session->GetArrayGlobalVar(fid,isNull);
...
SeeAlsoGetGlobalVarID|GetGlobalVarType|Get<type>GlobalVar|IsGlobalVarNull|IsGlobalVarObject|SetGlobalVarToNull
|Set<type>GlobalVar
IPB_Sessioninterface:IsGlobalVarNullmethod
DescriptionReturnstrueiftheglobalvariablecontainsanullvalue;otherwiseitreturnsfalse.
SyntaxIsGlobalVarNull(pbfieldfid)
Argument Description
fid ThefieldIDoftheglobalvariable
ReturnValuespbboolean.
ExamplesThesestatementstestwhetherthefieldidentifiedbyfidisaglobalvariablearray:fid=session->GetGlobalVarID("arr_gvar");
if(session->IsGlobalVarArray(fid))
{
arr_val=session->GetArrayGlobalVar(fid,isNull);
...
SeeAlsoGetGlobalVarID|GetGlobalVarType|Get<type>GlobalVar|IsGlobalVarArray|IsGlobalVarObject|SetGlobalVarToNull
|Set<type>GlobalVar
IPB_Sessioninterface:IsGlobalVarObjectmethod
DescriptionReturnstrueiftheglobalvariablecontainsanobject;otherwiseitreturnsfalse.
SyntaxIsGlobalVarObject(pbfieldfid)
Argument Description
fid ThefieldIDoftheglobalvariable
ReturnValuespbboolean.
ExamplesThesestatementstestwhetherthefieldidentifiedbyfidisaglobalvariableobject.Ifitis,itsvalueissettoanotherglobalvariableobject:fid=session->GetGlobalVarID("obj2_gvar");
if(session->IsGlobalVarObject(fid))
{
obj_val=session->GetObjectGlobalVar(fid,
isNull);
cls=session->GetClass(obj_val);
fid=session->GetFieldID(cls,"text");
s_val=session->GetStringField(obj_val,fid,
isNull);
mystr=session->GetString(s_val);
//Setthevalueofobj2_gvartoobj1_gvar
fid=session->GetGlobalVarID("obj1_gvar");
session->SetObjectGlobalVar(fid,obj_val);
}
SeeAlsoGetGlobalVarID
|GetGlobalVarType|Get<type>GlobalVar|IsGlobalVarArray|IsGlobalVarNull|SetGlobalVarToNull|Set<type>GlobalVar
IPB_Sessioninterface:IsNativeObjectmethod
DescriptionDetermineswhetherapbobjectisaninstanceofanativeclass.
SyntaxIsNativeObject(pbobjectobj)
Argument Description
obj Avalidobjecthandle
ReturnValuespbboolean.
ExamplesThef_getrowfunctionusesIsNativeObjecttotestwhetherextObjisanativeclass.Ifso,itgetsthenativeinterfaceandinvokesthef_getrowcountfunctionintheotherclass:longf_getrow(IPB_Session*session,pbobjectdwObj,
pbobjectextObj)
{
longlRet;
Imy_pbni*pImy_pbni=NULL;
IPBX_NonVisualObject*pp=NULL;
if(session->IsNativeObject(extObj))
{
pp=(IPBX_NonVisualObject*)session->
GetNativeInterface(extObj);
pImy_pbni=static_cast<Imy_pbni*>(pp);
lRet=pImy_pbni->f_GetRowCount(session,dwObj);
}
returnlRet;
}
Usage
UsethismethodinconjunctionwithGetNativeInterfacetoobtainadirectreferencetotheIPBX_UserObjectassociatedwithanothernativeclass,sothattheclassanditsmethodscanbeaccesseddirectly.
SeeAlsoGetNativeInterface
IPB_Sessioninterface:IsSharedVarArraymethod
DescriptionReturnstrueifthesharedvariablecontainsanarray;otherwiseitreturnsfalse.
SyntaxIsSharedVarArray(pbgroupgroup,pbfieldfid)
Argument Description
group Thegroupwhosesharedvariableistobeaccessed
fid ThefieldIDofthesharedvariable
ReturnValuespbboolean.
SeeAlsoGet<type>SharedVar|GetSharedVarID|GetSharedVarType|IsSharedVarNull|IsSharedVarObject|Set<type>SharedVar|SetSharedVarToNull
IPB_Sessioninterface:IsSharedVarNullmethod
DescriptionReturnstrueifthesharedvariablecontainsanullvalue;otherwiseitreturnsfalse.
SyntaxIsSharedVarNull(pbgroupgroup,pbfieldfid)
Argument Description
group Thegroupwhosesharedvariableistobeaccessed
fid ThefieldIDofthesharedvariable
ReturnValuespbboolean.
SeeAlsoGet<type>SharedVar|GetSharedVarID|GetSharedVarType|IsSharedVarArray|IsSharedVarObject|Set<type>SharedVar|SetSharedVarToNull
IPB_Sessioninterface:IsSharedVarObjectmethod
DescriptionReturnstrueifthesharedvariablecontainsanobject;otherwiseitreturnsfalse.
SyntaxIsSharedVarObject(pbgroupgroup,pbfieldfid)
Argument Description
group Thegroupwhosesharedvariableistobeaccessed
fid ThefieldIDofthesharedvariable
ReturnValuespbboolean.
SeeAlsoGet<type>SharedVar|GetSharedVarID|GetSharedVarType|IsSharedVarArray|IsSharedVarNull|Set<type>SharedVar|SetSharedVarToNull
IPB_Sessioninterface:NewBlobmethod
DescriptionCreatesanewblobandduplicatesabufferforthenewblobdata.
SyntaxNewBlob(constvoid*bin,pblonglen)
Argument Description
bin Avoidpointerthatpointstothesourcebuffer
len Thelengthinbytesofthedatainthebuffer
ReturnValuespbblob.
ExamplesIftheblobvalueinthePBCallInfostructureisnull,thiscodecreatesanewblobvaluewithfourbytesinthepArgumentsarray;otherwise,itsetstheblobvalueinthepArgumentsarraytothevalueinthePBCallInfostructure:if(ci->pArgs->GetAt(i)->IsNull())
pArguments[i].blob_val=
Session->NewBlob("null",4);
else
pArguments[i].blob_val=
ci->pArgs->GetAt(i)->GetBlob();
UsageThebuffercontainingthenewblobdataisfreedwhenPopLocalFrameiscalled.
SeeAlso
PopLocalFrame|SetBlob
IPB_Sessioninterface:NewBoundedObjectArraymethod
DescriptionCreatesaboundedPowerBuilderobjectorstructurearray.
SyntaxNewBoundedObjectArray(pbclasscls,pbuintdimension,PBArrayInfo::ArrayBound*
Argument Description
cls AvalidclasshandleofthetypeofPowerBuilderobjectorstructurearraytobecreated
dimension Anumbergreaterthanonethatindicatesthedimensionofthearraytobecreated
bounds Anarraycontainingtheupperandlowerboundariesofthearraytobecreated
ReturnValuespbarrayornullonfailure.
Examplesintsize;
pbarraypbin_a;
PBArrayInfo*ai;
PBXRESULTret;
pbclasscls;
pbgroupgroup;
size=sizeof(PBArrayInfo)+
sizeof(PBArrayInfo::ArrayBound);
ai=(PBArrayInfo*)malloc(size);
ai->bounds[0].upperBound=2;
ai->bounds[0].lowerBound=1;
ai->bounds[1].upperBound=2;
ai->bounds[1].lowerBound=1;
ai->numDimensions=2;
//Createnewarraypbin_a
group=session->FindGroup("w_main",pbgroup_window);
if(group==NULL)
return;
cls=session->FindClass(group,"commandbutton");
if(cls==NULL)
return;
pbin_a=session->NewBoundedObjectArray(cls,
ai->numDimensions,ai->bounds);
SeeAlsoGet<type>ArrayItem|GetArrayInfo|GetArrayItemType|GetArrayLength|IsArrayItemNull|NewBoundedSimpleArray|NewUnboundedObjectArray|NewUnboundedSimpleArray|ReleaseArrayInfo|Set<type>ArrayItem|SetArrayItemToNull|SetArrayItemValue
IPB_Sessioninterface:NewBoundedSimpleArraymethod
DescriptionCreatesaboundedsimpledataarray.
SyntaxNewBoundedSimpleArray(pbuinttype,pbuintdimension,PBArrayInfo::ArrayBound*
Argument Description
type Anenumeratedvariableoftypepbvalue_*indicatingthetypeofsimpleunboundedarraytobecreated
dimension Anumbergreaterthanonethatindicatesthedimensionofthearraytobecreated
bounds Anarraycontainingtheupperandlowerboundariesofthearraytobecreated
ReturnValuespbarrayornullonfailure.
SeeAlsoGet<type>ArrayItem|GetArrayInfo|GetArrayItemType|GetArrayLength|IsArrayItemNull|NewBoundedObjectArray|NewUnboundedObjectArray|NewUnboundedSimpleArray
|ReleaseArrayInfo|Set<type>ArrayItem|SetArrayItemToNull|SetArrayItemValue
IPB_Sessioninterface:NewDatemethod
DescriptionCreatesanewpbdatedataobject.
SyntaxNewDate()
ReturnValuespbdate.
ExamplesThisexampletestswhetheradatevalueexists,and,ifitdoesnot,itcreatesanewpbdateobjectandsetsitsvaluetothefirstdayinJanuary,1900:if(ci->pArgs->GetAt(0)->IsNull())
{
pArguments[i].date_val=Session->NewDate();
Session->SetDate(pArguments[i].date_val,
1900,1,1);//Date:1900-01-01
isNull[i]=true;
}
else
{
pArguments[i].date_val=
ci->pArgs->GetAt(i)->GetDate();
isNull[i]=false;
}
UsageTheinitialvalueis1900-1-1.
SeeAlsoSetDate
|SplitDate
IPB_Sessioninterface:NewDateTimemethod
DescriptionCreatesanewpbdatetimedataobject.
SyntaxNewDateTime()
ReturnValuespbdatetime.
ExamplesThisexampletestswhetheradate/timevalueexists,and,ifitdoesnot,itcreatesanewpbdateobjectandsetsitsvaluetothebeginningofJanuary,1900:if(ci->pArgs->GetAt(i)->IsNull())
{
pArguments[i].datetime_val=Session->NewDateTime();
Session->SetDateTime(pArguments[i].datetime_val,
1900,1,1,1,1,1);//Datetime:
//1900-01-0101:01:01
}
else
{
pArguments[i].datetime_val=
ci->pArgs->GetAt(i)->GetDateTime();
}
UsageTheinitialvalueis1900-1-10:0:0.0.
SeeAlsoSetDateTime|SplitDateTime
IPB_Sessioninterface:NewDecimalmethod
DescriptionAllocatesresourcesforanewdecimaldataobject.
SyntaxNewDecimal()
ReturnValuespbdecornullonfailure.
Examplesif(ci->pArgs->GetAt(i)->IsNull())
{
pArguments[i].dec_val=Session->NewDecimal();
Session->SetDecimal(pArguments[i].dec_val,"1.0");
}
else
pArguments[i].dec_val=
ci->pArgs->GetAt(i)->GetDecimal();
SeeAlsoGetDecimalString|ReleaseDecimalString|SetDecimal
IPB_Sessioninterface:NewObjectmethod
DescriptionCreatesanewobjectofthespecifiedtype.
SyntaxNewObject(pbclasscls)
Argument Description
cls Thetypeofobjectorstructureinstancetobecreated
ReturnValuespbobjectofthegivenclassorstructure.
Examplespbclasscls;
pbobjectex;
pbgroupgroup;
group=session->FindGroup
("user_exception",pbgroup_userobject);
if(group==NULL)
return;
cls=session->FindClass(group,"user_exception");
if(group==NULL)
return;
ex=session->NewObject(cls);
UsageThereturnedobject'slifecycleisrestrictedtothecurrentframeunlessAddGlobalRefiscalledontheobject.
SeeAlsoFindClass
|FindGroup
IPB_Sessioninterface:NewProxyObjectmethod
DescriptionCreatesaproxyforaremoteobject.TheproxyisusedtoextendthenetworkprotocolinPowerBuilder.
SyntaxNewProxyObject(pbclasscls)
Argument Description
cls Thetypeofobjectorstructureinstancetobecreated
ReturnValuespbproxyobject.
ExamplesThisexamplecreatesanewproxyobject,createsamarshaler,andassociatesthemarshalerwiththeproxyobject:pbproxyObjectproxy=session->NewProxyObject(cls);
if(proxy==NULL)
{
ci->returnValue->SetLong(kFailToCreateProxy);
returnPBX_OK;
}
//CreateMyMarshaler
MyMarshaler*marshaler=newMyMarshaler(env,
proxy,obj);
//AssociateMyMarshalerwiththeproxy
session->SetMarshaler(proxy,marshaler);
ci->pArgs->GetAt(0)->SetObject(proxy);
ci->returnValue->SetLong(kSuccessful);
returnPBX_OK;
SeeAlsoGetMarshaler|SetMarshaler
IPB_Sessioninterface:NewStringmethod
DescriptionCreatesanewstring.
SyntaxNewString(LPCTSTR)
ReturnValuespbstring.
Examplespbclasscls;
cls=session->GetSystemFunctionsClass();
if(cls==NULL)
{
ret_val=session->NewString("null");
returnret_val;
}
UsageThereturnedstringisdestroyedwhenPopLocalFrameiscalled.
SeeAlsoSetString
IPB_Sessioninterface:NewTimemethod
DescriptionCreatesanewpbtimedataobject.
SyntaxNewTime()
ReturnValuespbtime.
ExamplesThesestatementssplitatimeintohours,minutes,andseconds,andthenusetheresultingvaluestosetthevalueofanewtimeobject:Session->SplitTime(ci.returnValue->GetTime(),&hh,
&mm,&ss);
ret_val=Session->NewTime();
Session->SetTime(ret_val,hh,mm,ss);
UsageTheinitialvalueis0:0:0.0.
SeeAlsoSetTime|SplitTime
IPB_Sessioninterface:NewUnboundedObjectArraymethod
DescriptionCreatesanunboundedPowerBuilderobjectorstructuredataarray.
SyntaxNewUnboundedObjectArray(pbclasscls)
Argument Description
cls AvalidclasshandleofthetypeofPowerBuilderobjectorstructurearraytobecreated
ReturnValuespbarrayornullonfailure.
UsageAnunboundedarraycanhaveonlyonedimension,sonodimensioninformationisneeded.
SeeAlsoGet<type>ArrayItem|GetArrayInfo|GetArrayItemType|GetArrayLength|IsArrayItemNull|NewBoundedObjectArray|NewBoundedSimpleArray|NewUnboundedSimpleArray|ReleaseArrayInfo
|Set<type>ArrayItem|SetArrayItemToNull|SetArrayItemValue
IPB_Sessioninterface:NewUnboundedSimpleArraymethod
DescriptionCreatesanunboundedsimpledataarray.
SyntaxNewUnboundedSimpleArray(pbuinttype)
Argument Description
type Anenumeratedvariableoftypepbvalue_*indicatingthetypeofsimpleunboundedarraytobecreated
ReturnValuespbarrayornullonfailure.
ExamplesThisexamplecreatesanunboundedsimpledataarrayofthetypereturnedbythegetDataTypemethod,whichreturnsastringoftheformdt_type.Mostofthecasestatementshavebeenremovedforthesakeofbrevity:if(d_returnType.isArray())
{
returnValue.l=env->CallObjectMethodA(obj,
mid,values.get());
pbarrayv;
switch(d_returnType.getDataType())
{
casedt_boolean:
v=session->NewUnboundedSimpleArray
(pbvalue_boolean);
break;
casedt_short:
v=session->NewUnboundedSimpleArray
(pbvalue_int);
break;
//CASEstatementsomitted
...
default:
v=session->NewUnboundedSimpleArray
(pbvalue_any);
break;
}
ci->returnValue->SetArray(v);
UsageAnunboundedarraycanhaveonlyonedimension,sonodimensioninformationisneeded.
SeeAlsoGet<type>ArrayItem|GetArrayInfo|GetArrayItemType|GetArrayLength|IsArrayItemNull|NewBoundedObjectArray|NewBoundedSimpleArray|NewUnboundedObjectArray|ReleaseArrayInfo|Set<type>ArrayItem|SetArrayItemToNull|SetArrayItemValue
IPB_Sessioninterface:PopLocalFramemethod
DescriptionPopsthecurrentlocalreferenceframefromthecurrentnativemethodstackframe,removingalllocalreferencestotheobjectsaddedinthatlocalframe.Allthepbobject,pbstring,andpbdecimalvariablescreatedbycallingNewDecimal,NewObject,orNewStringinthecurrentframearedestroyedautomatically.
SyntaxPopLocalFrame()
ReturnValuesNone.
SeeAlsoAddLocalRef|PushLocalFrame|RemoveLocalRef
IPB_Sessioninterface:ProcessPBMessagemethod
DescriptionChecksthePowerBuildermessagequeueand,ifthereisamessageinthequeue,attemptstoprocessit.
SyntaxProcessPBMessage()
ReturnValuespbboolean.ReturnstrueifaPowerBuildermessagewasprocessed,andfalseotherwise.
ExamplesThismessageloopinaWinMainfunctionprocessesaPowerBuildermessageifamessagehasbeenreceivedandanIPBsessionisrunning:try
{
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
//CalltoProcessPBMessage
if(session)
session->ProcessPBMessage();
}
ThisoverloadedWindowProcfunctioninanMFCapplicationprocessesaPowerBuildermessage:LRESULTCCallPBVCtrl::WindowProc(UINTmessage,
WPARAMwParam,LPARAMlParam)
{
d_session->ProcessPBMessage();
returnCDialog::WindowProc(message,wParam,lParam);
}
Usage
Eachtimethisfunctioniscalled,itattemptstoretrieveamessagefromthePowerBuildermessagequeueandprocessit.ItissimilartothePowerBuilderYieldfunction;however,ProcessPBMessageprocessesonlyonemessageatatime,anditprocessesonlyPowerBuildermessages.TheYieldfunctionalsoprocessesWindowsmessages.UsethisfunctionwhenPowerBuilderwindowsorvisualcontrolsarecalledfromC++applicationsorfromextensionstoensurethateventspostedtothePowerBuildermessagequeueareprocessed.IfthefunctionisnotinsertedintheC++applicationinawaythatresultsinitbeingcalledrepeatedly,postedeventsarenotprocessedinthePowerBuilderapplication.Formostapplications,ProcessPBMessagecanbeinsertedinamessageloopintheWinMainfunction.IfyouuseMicrosoftFoundationClasses(MFC),youcannotmodifythebuilt–inmessageloop.ToensurethattheProcessPBMessagefunctioniscalledrepeatedly,youcanoverloadtheCWnd::WindowProcfunctionandinsertProcessPBMessageintotheoverloadedfunction.
IPB_Sessioninterface:PushLocalFramemethod
DescriptionPushesalocalreferenceframeontothecurrentnativemethodstackframe.AlocalframeisanalogoustoascopeinC++.
SyntaxPushLocalFrame()
ReturnValuesNone.
SeeAlsoPopLocalFrame|RemoveLocalRef
IPB_Sessioninterface:Releasemethod
DescriptionReleasesthecurrentIPB_Session.TheIPB_Sessionobjectbecomesinvalidafterthecall.
SyntaxRelease()
ReturnValuesNone.
ExamplesThisexampleshowsacalltoRelease.Theexamplecheckswhetherthereisavalidsessionobjectbeforeattemptingtoreleaseit:if(pIPB_ObjectFactory)
{
pIPB_ObjectFactory->Release();
pIPB_ObjectFactory=NULL;
}
IPB_Sessioninterface:ReleaseArrayInfomethod
DescriptionReleasesmemoryreturnedbyGetArrayInfo.
SyntaxReleaseArrayInfo(PBArrayInfo*pbarrayinfo)
Argument Description
pbarrayinfoAvalidPBArrayInfohandle
ReturnValuesPBXRESULT.PBX_OKforsuccess.
ExamplesThisexampleshowshowReleaseArrayInfoshouldbecalledwhenmemoryallocatedbyGetArrayInfoisnolongerneeded:PBArrayInfo*ai;
...
session->ReleaseArrayInfo(ai);
UsageIfthearrayisanunboundedarray,theboundsinformationinPBArrayInfoisundetermined.
SeeAlsoGet<type>ArrayItem|GetArrayInfo|GetArrayItemType|GetArrayLength|IsArrayItemNull
|NewBoundedObjectArray|NewBoundedSimpleArray|NewUnboundedObjectArray|NewUnboundedSimpleArray|Set<type>ArrayItem|SetArrayItemToNull|SetArrayItemValue
IPB_Sessioninterface:ReleaseDateStringmethod
DescriptionFreesthememoryacquiredusingGetDateString.
SyntaxReleaseDateString(LPCTSTRstring)
Argument Description
string Thestringtobereleasedfrommemory
ReturnValuesNone.
SeeAlsoGetDateString
IPB_Sessioninterface:ReleaseDateTimeStringmethod
DescriptionFreesthememoryacquiredusingGetDateTimeString.
SyntaxReleaseDateTimeString(LPCTSTRstring)
Argument Description
string Thestringtobereleasedfrommemory
ReturnValuesNone.
SeeAlsoGetDateTimeString
IPB_Sessioninterface:ReleaseDecimalStringmethod
DescriptionFreesthememoryacquiredusingGetDecimalString.
SyntaxReleaseDecimalString(LPCTSTRstring)
Argument Description
string Thestringtobereleasedfrommemory
ReturnValuesNone.
SeeAlsoGetDecimalString
IPB_Sessioninterface:ReleaseResultSetAccessormethod
DescriptionReleasesthepointerobtainedusingGetResultSetAccessor.
SyntaxReleaseResultSetAccessor(IPB_ResultSetAccessor*rs)
Argument Description
rs ApointertotheIPB_ResultSetAccessorobjecttobereleased
ReturnValuesNone.
ExamplesThisstatementreleasestheIPB_ResultSetAccessorobjectrsa:Session->ReleaseResultSetAccessor(rsa);
UsageWhenyoucallReleaseResultSetAccessor,theReleasefunctionoftheIPB_ResultSetAccessorinterfaceiscalledonthersargumenttoreleasetheinterfacepointer.
SeeAlsoCreateResultSet|GetResultSetAccessor
IPB_Sessioninterface:ReleaseStringmethod
DescriptionFreesthememoryacquiredusingGetString,GetClassName,GetFieldName,orGetEnumItemName.
SyntaxReleaseString(LPCTSTRstring)
Argument Description
string Thestringtobereleasedfrommemory
ReturnValuesNone.
ExamplesThefollowingexamplegetsapointertoeachoftwostringspassedinasarguments,concatenatestheminanewstring,thenreleasesthememoryusedbytheoriginalstrings:pbstringpsppcls::f_add_string(IPB_Session*session,pbstringarg1,pbstringarg2)
{
LPCTSTRpStr1,pStr2;
TCHARtmp[100];
pbstringret;
pStr1=session->GetString(arg1);
pStr2=session->GetString(arg2);
_tcscpy(tmp,pStr1);
_tcscat(tmp,pStr2);
ret=session->NewString(tmp);
session->ReleaseString(pStr1);
session->ReleaseString(pStr2);
returnret;
}
UsageDonotusethisfunctiontoreleaseastringobtainedusingGetDateString,GetTimeString,GetDateTimeString,orGetDecimalString.EachoftheseGetmethodshasacorrespondingReleasemethod.
SeeAlsoGetClassName|GetEnumItemName|GetFieldName|GetString
IPB_Sessioninterface:ReleaseTimeStringmethod
DescriptionFreesthememoryacquiredusingGetTimeString.
SyntaxReleaseTimeString(LPCTSTRstring)
Argument Description
string Thestringtobereleasedfrommemory
ReturnValuesNone.
SeeAlsoGetTimeString
IPB_Sessioninterface:ReleaseValuemethod
DescriptionFreestheIPB_ValueacquiredusingAcquireValueorAcquireArrayItemValue.
SyntaxReleaseValue(IPB_Value*value)
Argument Description
value Thestringtobereleasedfrommemory
ReturnValuesNone.
ExamplesTheAcquireValuemethodisusedtoobtainamessageargumentvalue.Later,whenthevalueisnolongerneeded,itisreleasedusingReleaseValuetoavoidmemoryleaks://Acquireavalue
MessageArg=session->AcquireValue
(ci->pArgs->GetAt(0));
pbstringpbMessage=MessageArg->GetString();
Message=(LPSTR)session->GetString(pbMessage);
...
//Cleanupphase
if(MessageArg)
{
Session->ReleaseValue(MessageArg);
}
UsageWhenyounolongerneedthedataacquiredusingtheAcquireValueorAcquireArrayItemValuemethod,youmustcalltheReleaseValuemethodtofreethedata.Failingtodosocausesamemoryleak.
DonotuseReleaseValuetoreleaseavaluethatwasnotacquiredusingAcquireValueorAcquireArrayItemValue.Ifyoudo,thePowerBuilderVMmightcrash.
SeeAlsoAcquireArrayItemValue|AcquireValue
IPB_Sessioninterface:RemoveGlobalRefmethod
DescriptionRemovesaglobalreferencetothespecifiedPowerBuilderobject.
SyntaxRemoveGlobalRef(pbobjectobj)
Argument Description
obj AvalidPowerBuilderobjecthandle
ReturnValuesNone.
ExamplesvoidMyPBNIClass::reference()
{
d_session->AddGlobalRef(d_pbobject);
}
voidMyPBNIClass::unreference()
{
if(d_pbobject!=NULL)
d_session->RemoveGlobalRef(d_pbobject);
}
SeeAlsoAddGlobalRef
IPB_Sessioninterface:RemoveLocalRefmethod
DescriptionRemovesalocalreferencetothespecifiedPowerBuilderobject.
SyntaxRemoveLocalRef(pbobjectobj)
Argument Description
obj AvalidPowerBuilderobjecthandle
ReturnValuesNone.
SeeAlsoAddLocalRef|PopLocalFrame|PushLocalFrame
IPB_Sessioninterface:RemovePropmethod
DescriptionRemovesthespecifiedvariablefromthelistofpropertiesofthecurrentIPBsession.Youmustfreethememorytowhichthepropertypoints.
SyntaxRemoveProp(LPCTSTRname)
Argument Description
name Thenameofthevariabletoberemoved
ReturnValuesNone.
ExamplesThesestatementsremoveprop_namefromthelistofvariablesassociatedwiththesessionanddeletethepointercreatedtopointtothevariablesvalue:session->RemoveProp(prop_name);
deleteSetValue;
UsageSetPropenablesyoutouseavariablevaluethroughoutanIPBsession.UseRemoveProptoremovethevariablefromthelistofvariablesassociatedwiththesessionwhenitisnolongerneeded.Youmustalsofreethememoryassociatedwiththevariable.
SeeAlsoGetProp|SetProp
IPB_Sessioninterface:RestartRequestedmethod
DescriptionDetermineswhetherthePowerBuildersystemfunctionRestarthasbeencalled.
SyntaxHasPBVisualObject()
ReturnValuespbboolean.ReturnstruewhenthePowerBuildersystemfunctionRestartiscalled.WhenRestartRequestedreturnstrue,youshoulddestroytheexistingIPB_Sessionobjectandcreateanewonetorestarttheapplication.
ExamplesInthefollowingexample,StartApplication,RecreateSession,andCleanApplicationarefunctionsofthePB_MyConsoleAppRunnerclass.StartApplicationissimilartotheIP_VMRunApplicationfunction,butitusesanexistingsession.RecreateSessionreleasesthecurrentsessionandcreatesanewone.CleanApplicationtriggerstheapplication'sCloseeventandreleasesresources.Intheexample,RestartRequestediscalledinaDOlooptotestwhetherthePowerBuilderRestartfunctionhasbeencalled.Ifithas,theRecreateSessionfunctioniscalled:PBXRESULTPB_MyConsoleAppRunner::RunApplication()
{
PBXRESULTres;
pbbooleanrestart=FALSE;
do
{
res=StartApplication();
if(res!=PBX_OK)
break;
restart=GetSession()->RestartRequested();
if(restart)
RecreateSession();
}while(restart);
returnCleanApplication();
}
UsageRestartRequestedandHasVisualPBObjectareusedintheimplementationoftheIPB_VMRunApplicationfunction.YounolongerneedtouseanexternalmessagelooptocheckforWindowsmessageswhenyoucalltheRunApplicationfunctionasyoudidinversionsofPBNIpriortoPowerBuilder10.5.
SeeAlsoHasPBVisualObject|RunApplication
IPB_Sessioninterface:Set<type>ArrayItemmethod
DescriptionAssignsavaluetoanarrayitemofaspecifictype.
SyntaxSetBlobArrayItem(pbarrayarray,pblongdim[],pbblobvalue)
SetBoolArrayItem(pbarrayarray,pblongdim[],pbbooleanvalue)
SetByteArrayItem(pbarrayarray,pblongdim[],pbbytevalue)
SetCharArrayItem(pbarrayarray,pblongdim[],pbcharvalue)
SetDateArrayItem(pbarrayarray,pblongdim[],pbdatevalue)
SetDateTimeArrayItem(pbarrayarray,pblongdim[],pbdatetimevalue
SetDecArrayItem(pbarrayarray,pblongdim[],pbdecvalue)
SetDoubleArrayItem(pbarrayarray,pblongdim[],pbdoublevalue)
SetIntArrayItem(pbarrayarray,pblongdim[],pbintvalue)
SetLongArrayItem(pbarrayarray,pblongdim[],pblongvalue)
SetLongLongArrayItem(pbarrayarray,pblonglongdim[],pblongvalue
SetObjectArrayItem(pbarrayarray,pblongdim[],pbobjectobj)
SetPBStringArrayItem(pbarrayarray,pblongdim[],pbstringvalue)
SetRealArrayItem(pbarrayarray,pblongdim[],pbrealvalue)
SetStringArrayItem(pbarrayarray,pblongdim[],LPCTSTRvalue)
SetTimeArrayItem(pbarrayarray,pblongdim[],pbtimevalue)
SetUintArrayItem(pbarrayarray,pblongdim[],pbuintvalue)
SetUlongArrayItem(pbarrayarray,pblongdim[],pbulongvalue)
Argument Description
array Avalidpbarrayhandle.
dimApblongarraytoholdindexesofeachdimension.Thenumberofdimensionsmustequalthenumberofdimensionsofthearray.
value Thenewvalueofthearrayitem.
ReturnValuesPBXRESULT.PBX_OKforsuccess.Iftheindexexceedstheboundsofaboundedarray,itreturnsPBX_E_ARRAY_INDEX_OUTOF_BOUNDS.Ifthedatapassedindoesnotmatchthedatatypeofthearray,itreturnsPBX_E_MISMATCHED_DATA_TYPE.
ExamplesThisexamplecreatesanewunboundedsimplearray.IntheFORloop,application-specificcode(notshownhere)getsarrayvalues,whicharethenaddedtothearrayusingSetPBStringArrayItem:pblongdim[1];
char*cstr;
pbuintnumDimensions=1;
PBArrayInfo::ArrayBoundbound;
bound.lowerBound=1;
bound.upperBound=size;
d_pbarray=d_session->NewBoundedSimpleArray
(pbvalue_string,numDimensions,&bound);
for(inti=1;i<=size;i++)
{
dim[0]=i;
//addapplication-specificcodehereto
//getarrayvalue
pbstringpValue=d_session->NewString(cstr);
d_session->SetPBStringArrayItem(d_pbarray,dim,
pValue);
delete[]cstr;
}
pbv.SetArray(d_pbarray);
UsageThismethodassignstheIPB_ValuepointedtobythevalueargumenttothearrayiteminthesamewaythattheIPB_ValueSet<type>methodsetsavalue.
SeeAlsoGet<type>ArrayItem|GetArrayInfo|GetArrayItemType|GetArrayLength|IsArrayItemNull|NewBoundedObjectArray|NewBoundedSimpleArray|NewUnboundedObjectArray|NewUnboundedSimpleArray|ReleaseArrayInfo|SetArrayItemToNull|SetArrayItemValue
IPB_Sessioninterface:Set<type>Fieldmethod
DescriptionAsetofmethodsthatsetanewvalueinaninstancefieldofanobject.
SyntaxSetArrayField(pbobjectobj,pbfieldIDfid,pbarrayvalue)
SetBlobField(pbobjectobj,pbfieldIDfid,pbblobvalue)
SetBoolField(pbobjectobj,pbfieldIDfid,pbbooleanvalue)
SetByteField(pbobjectobj,pbfieldIDfid,pbbytevalue)
SetCharField(pbobjectobj,pbfieldIDfid,pbcharvalue)
SetDateField(pbobjectobj,pbfieldIDfid,pbdatevalue)
SetDateTimeField(pbobjectobj,pbfieldIDfid,pbdatetimevalue)
SetDecField(pbobjectobj,pbfieldIDfid,pbdecvalue)
SetDoubleField(pbobjectobj,pbfieldIDfid,pbdoublevalue)
SetIntField(pbobjectobj,pbfieldIDfid,pbintvalue)
SetLongField(pbobjectobj,pbfieldIDfid,pblongvalue)
SetLongLongField(pbobjectobj,pbfieldIDfid,pblonglongvalue)
SetObjectField(pbobjectobj,pbfieldIDfid,pbobjectvalue)
SetPBStringField(pbobjectobj,pbfieldIDfid,pbstringvalue)
SetRealField(pbobjectobj,pbfieldIDfid,pbrealvalue)
SetStringField(pbobjectobj,pbfieldIDfid,LPCTSTRvalue)
SetTimeField(pbobjectobj,pbfieldIDfid,pbtimevalue)
SetUintField(pbobjectobj,pbfieldIDfid,pbuintvalue)
SetUlongField(pbobjectobj,pbfieldIDfid,pbulongvalue)
Argument Description
obj Thehandleoftheobjectwhosefieldistobeaccessed
fid ThefieldIDofthespecifiedobject
value Thevaluetobeset
ReturnValuesPBX_RESULT.
ExamplesThesestatementssetanewstringvalueinastringfield:pbstringstr=session->NewString(d_message.c_str());
if(str!=NULL)
session->SetPBStringField(d_pbobj,d_fidMsg,str);
UsageWhenyouchangeanyvisualpropertyofaPowerBuilderobjectbycallingSet<type>fieldfunctions,thepropertyischangedbutthepropertyisnotrefreshedinthegraphicaluserinterface.UpdateFieldrefreshesthevisualpropertiesofPowerBuilderobjects.YoumustcallUpdateFieldexplicitlywhenchanginganyvisualpropertywiththeSet<type>fieldfunctions.
SeeAlsoGetFieldID|GetFieldType|Get<type>Field|GetNumOfFields|IsFieldArray|IsFieldNull|IsFieldObject|SetFieldToNull|UpdateField
IPB_Sessioninterface:Set<type>GlobalVarmethod
DescriptionAsetofmethodsthatsetthevalueofaglobalvariableofaspecificdatatype.
SyntaxSetArrayGlobalVar(pbfieldIDfid,pbarrayvalue)
SetBlobGlobalVar(pbfieldIDfid,pbblobvalue)
SetBoolGlobalVar(pbfieldIDfid,pbbooleanvalue)
SetByteGlobalVar(pbfieldIDfid,pbbytevalue)
SetCharGlobalVar(pbfieldIDfid,pbcharvalue)
SetDateGlobalVar(pbfieldIDfid,pbdatevalue)
SetDateTimeGlobalVar(pbfieldIDfid,pbdatetimevalue)
SetDecGlobalVar(pbfieldIDfid,pbdecvalue)
SetDoubleGlobalVar(pbfieldIDfid,pbdoublevalue)
SetIntGlobalVar(pbfieldIDfid,pbintvalue)
SetLongGlobalVar(pbfieldIDfid,pblongvalue)
SetLongLongGlobalVar(pbfieldIDfid,pblonglongvalue)
SetObjectGlobalVar(pbfieldIDfid,pbobjectvalue)
SetPBStringGlobalVar(pbfieldIDfid,pbstringvalue)
SetRealGlobalVar(pbfieldIDfid,pbrealvalue)
SetStringGlobalVar(pbfieldIDfid,LPCTSTRvalue)
SetTimeGlobalVar(pbfieldIDfid,pbtimevalue)
SetUintGlobalVar(pbfieldIDfid,pbuintvalue)
SetUlongGlobalVar(pbfieldIDfid,pbulongvalue)
Argument Description
fid ThefieldIDoftheglobalvariable
value Thevaluetobeset
ReturnValuesPBX_RESULT.
ExamplesThisshowshowtoadd1tothevalueofaglobalvariable:fid=session->GetGlobalVarID("l_gvar");
l_val=session->GetLongGlobalVar(fid,isNull);
session->SetLongGlobalVar(fid,l_val+1);
SeeAlsoGetGlobalVarID|GetGlobalVarType|Get<type>GlobalVar|IsGlobalVarObject|SetGlobalVarToNull
IPB_Sessioninterface:Set<type>SharedVarmethod
DescriptionAsetofmethodsthatsetthevalueofasharedvariableofaspecificdatatype.
SyntaxSetArraySharedVar(pbgroupgroup,pbfieldIDfid,pbarrayvalue)
SetBlobSharedVar(pbgroupgroup,pbfieldIDfid,pbblobvalue)
SetBoolSharedVar(pbgroupgroup,pbfieldIDfid,pbbooleanvalue)
SetByteSharedVar(pbgroupgroup,pbfieldIDfid,pbbytevalue)
SetCharSharedVar(pbgroupgroup,pbfieldIDfid,pbcharvalue)
SetDateSharedVar(pbgroupgroup,pbfieldIDfid,pbdatevalue)
SetDateTimeSharedVar(pbgroupgroup,pbfieldIDfid,pbdatetimevalue
SetDecSharedVar(pbgroupgroup,pbfieldIDfid,pbdecvalue)
SetDoubleSharedVar(pbgroupgroup,pbfieldIDfid,pbdoublevalue)
SetIntSharedVar(pbgroupgroup,pbfieldIDfid,pbintvalue)
SetLongSharedVar(pbgroupgroup,pbfieldIDfid,pblongvalue)
SetLongLongSharedVar(pbgroupgroup,pbfieldIDfid,pblonglongvalue
SetObjectSharedVar(pbgroupgroup,pbfieldIDfid,pbobjectvalue)
SetPBStringSharedVar(pbgroupgroup,pbfieldIDfid,pbstringvalue)
SetRealSharedVar(pbgroupgroup,pbfieldIDfid,pbrealvalue)
SetStringSharedVar(pbgroupgroup,pbfieldIDfid,LPCTSTRvalue)
SetTimeSharedVar(pbgroupgroup,pbfieldIDfid,pbtimevalue)
SetUintSharedVar(pbgroupgroup,pbfieldIDfid,pbuintvalue)
SetUlongSharedVar(pbgroupgroup,pbfieldIDfid,pbulongvalue)
Argument Description
group Thegroupwhosesharedvariableistobeaccessed
fid ThefieldIDofthesharedvariable
value Thevaluetobeset
ReturnValuesPBX_RESULT.
SeeAlsoGet<type>SharedVar|GetSharedVarID|GetSharedVarType|IsSharedVarArray|IsSharedVarNull|IsSharedVarObject|SetSharedVarToNull
IPB_Sessioninterface:SetArrayItemToNullmethod
DescriptionSetsthevalueofanarrayitemtoanullvalue.
SyntaxSetArrayItemToNull(pbarrayarray,pblongdim[])
Argument Description
array Avalidpbarraystructureinwhichyouwanttosetanarrayitemtonull.
dimApblongarraytoholdtheindexesofeachdimensionofthearray.Thesizeofthearraymustequalthedimensionsofarray.
ReturnValuespbboolean.
SeeAlsoIsArrayItemNull
IPB_Sessioninterface:SetArrayItemValuemethod
DescriptionSetsthevalueofanarrayitemtothevalueofanIPB_Value.
SyntaxSetArrayItemValue(pbarrayarray,pblongdim[],IPB_Value*src)
Argument Description
array Avalidpbarraystructureinwhichyouwanttosetanarrayitemtonull.
dimApblongarraytoholdtheindexesofeachdimensionofthearray.Thesizeofthearraymustequalthedimensionsofarray.
src Thevaluetowhichthearrayitemistobechanged.
ReturnValuesNone.
ExamplesThiscodesetsthevalueofeachiteminanarray:for(i=1;i<=bound;i++)
{
dim[0]=i;
ipv=Session->AcquireArrayItemValue(refArg,dim);
Session->SetArrayItemValue(*i_array,dim,ipv);
Session->ReleaseValue(ipv);
}
UsageTheSetArrayItemValuemethoddoesnotverifythatthedatatypeofthereplacementvaluematchesthedatatypeoftheoriginalvalue.
SeeAlsoAcquireArrayItemValue|ReleaseValue|SetArrayItemToNull|SetValue
IPB_Sessioninterface:SetBlobmethod
DescriptionDestroystheexistingdatainablobandcopiesdataintoitfromabuffer.
SyntaxSetBlob(pbblobblb,constvoid*bin,pblonglen)
Argument Description
blb Avalidpbblobobjectwhosevalueistobereset
bin Apointertothesourcebuffer
len Thelengthinbytesofthedatainthebuffer
ReturnValuesPBXRESULT.ReturnsPBX_OKforsuccessorPBX_E_INVALID_ARGUMENTifthenewblobvalueisinvalid;otherwise,returnsPBX_E_OUTOF_MEMORY.
UsageAdeepcopyisperformed.Theexistingvalueisdestroyedfirst,andthenthecontentsofthebinargumentarecopiedintoanewvalue.
SeeAlsoNewBlob
IPB_Sessioninterface:SetDatemethod
DescriptionResetsthevalueofthespecifiedpbdateobject.
SyntaxSetDate(pbdatedate,pbintyear,pbintmonth,pbintday)
Argument Description
date Thepbdateobjecttobereset
year Ayearintherange1000to3000
month Amonthintherange1to12
day Adayintherange1to31
ReturnValuesPBX_RESULT.PBX_OKforsuccessorPBX_E_INVALID_ARGUMENTifthenewdateisinvalid.
ExamplesThisexamplesetsthedatetoMarch12,1938:session->SetDate(date_val,1938,3,12);
UsageIftheparametersareinvalid,thedateisresetto1900-1-1.
SeeAlsoNewDate|SplitDate
IPB_Sessioninterface:SetDateTimemethod
DescriptionResetsthevalueofthespecifiedpbdatetimeobject.
SyntaxSetDate(pbdatetimedt,pbintyear,pbintmonth,pbintday,pbinthour
Argument Description
dt Thepbdatetimeobjecttobereset
year Ayearintherange1000to3000
month Amonthintherange1to12
day Adayintherange1to31
hour Anhourintherange0to23
minute Aminuteintherange0to59
second Asecondintherange0to59.999999
ReturnValuesPBX_RESULT.PBX_OKforsuccessorPBX_E_INVALID_ARGUMENTifthenewdatetimeisinvalid.
ExamplesThisexamplesetsthedatetimevaluetoAugust19,1982at10:30:45.10:session->SetDate(date_val,1982,8,19,10,30,45.1);
UsageIftheparametersareinvalid,thedatetimevalueisresetto1900-1-1
0:0:0.0.
SeeAlsoNewDateTime|SplitDateTime
IPB_Sessioninterface:SetDecimalmethod
DescriptionSetsthevalueofadecimalvariabletodecimaldatainastring.
SyntaxSetDecimal(pbdecdec,LPCTSTRdec_str)
Argument Description
dec Thedecimaldataobjecttobeset
dec_str Thestringcontainingthedatatobeconvertedtoadecimal
ReturnValuesPBXRESULT.PBX_OKforsuccess.
ExamplesThisexampleusestheIPB_SessionSetDecimalmethodtosetthevalueofavariableoftypepbdec,thenusestheIPB_ValueSetDecimalmethodtosetthereturnvalueinthePBCallInfostructure:pbdecpbdecRet=NULL;
LPTSTRlpDecValueToReturn=NULL;
...
pbdecRet=session->NewDecimal();
session->SetDecimal(pbdecRet,
(LPCTSTR)lpDecValueToReturn);
ci->returnValue->SetDecimal(pbdecRet);
UsageIfthestringcontainsinvaliddata,thedecimalvalueissetto0.0.
SeeAlsoGetDecimalString
|NewDecimal|ReleaseDecimalString
IPB_Sessioninterface:SetFieldToNullmethod
DescriptionSetsthevalueofthespecifiedfieldtonull.
SyntaxSetFieldToNull(pbobjectobj,pbfieldfid)
Argument Description
obj Avalidobjecthandle
fid ThefieldIDofthespecifiedobject
ReturnValuesNone.
SeeAlsoGetFieldID|GetFieldType|Get<type>Field|GetNumOfFields|IsFieldArray|IsFieldNull|IsFieldObject|Set<type>Field
IPB_Sessioninterface:SetGlobalVarToNullmethod
DescriptionSetsthevalueofthespecifiedglobalvariabletonull.
SyntaxSetGlobalVarToNull(pbobjectobj,pbfieldfid)
Argument Description
fid ThefieldIDoftheglobalvariable
ReturnValuesNone.
SeeAlsoGetGlobalVarID|GetGlobalVarType|Get<type>GlobalVar|IsGlobalVarArray|IsGlobalVarNull|IsGlobalVarObject|Set<type>GlobalVar
IPB_Sessioninterface:SetMarshalermethod
DescriptionSetsamarshalerthatwillbeusedtoinvokeremotemethodsandconvertPowerBuilderdataformatstotheuser'scommunicationprotocol.
SyntaxSetMarshaler(pbproxyObjectobj,IPBX_Marshaler*marshaler)
Argument Description
obj AnobjectoftypepbproxyObjecttobeusedasaproxyforaremoteobjectthatwascreatedusingNewProxyObject
marshaler AclassinheritedfromIPBX_Marshaler
ReturnValuesNone.
ExamplesThisexamplecreatesaJavaMarshalerclassandassociatesitwithaproxyobject://CreateJavaMarshaler
JavaMarshaler*marshaler=newJavaMarshaler(env,
proxy,jobj);
//AssociatetheJavaMarshalerwiththePBproxy
session->SetMarshaler(proxy,marshaler);
ci->pArgs->GetAt(0)->SetObject(proxy);
ci->returnValue->SetLong(kSuccessful);
returnPBX_OK;
UsageTheSetMarshalerfunctionassociatesanobjectoftypeIPBX_Marshaler
withaPBProxyobject.Itispossibletoassociatemultiplemarshalerobjectswithasingleproxyobject.Itisalsopossibletoassociateonemarshalerobjectwithmultipleproxyobjects.Neitheroftheseisgoodcodingpracticeandshouldbeavoided.BeforecallingSetMarshaler,youcancalltheIPB_SessionGetMarshalerfunctiontoobtainanexistingmarshalerobjectassociatedwithagivenproxyobject,andthendestroytheexistingmarshalerobjectbeforeassociatinganewmarshalerwiththeproxy.Whenaproxyobjectisdestroyed,itcallstheassociatedmarshalerobject'sDestroymethod.Ifmultipleproxyobjectsareassociatedwithasinglemarshalerobject,youneedtoimplementsomeformofreferencecounting.Otherwise,themarshalerobjectisdestroyedwhenthefirstassociatedproxyobjectisdestroyed,andsubsequentcallstothemarshalerobject'sDestroymethod,whenotherassociatedproxyobjectsaredestroyed,willthrowexceptions.Toavoidtheseissues,thereshouldbeaone-to-onerelationshipbetweenmarshalerandproxyobjects.
SeeAlsoGetMarshaler|GetMethodID
IPB_Sessioninterface:SetPropmethod
DescriptionAddsanewvariabletothelistofpropertiesofthecurrentsessionorchangesthevalueofanexistingvariable.
SyntaxSetProp(LPCTSTRname,void*data)
Argument Description
name Thenameofthepropertytobeset
data Apointertothedatabufferwherethevariable'svalueresides
ReturnValuesNone.
ExamplesInthisexample,thenativeclasshastwofunctions.ThisistheirdescriptionpassedinthePBX_GetDescriptionfunction:"subroutinef_setprop(inta)\n"
"functionintf_getprop()\n"
Thefunctionsareassociatedwiththeseenumeratedvalues:enumMethodIDs
{
mid_SetProp=0,
mid_GetProp=1
};
Whenthef_setpropfunctioniscalledfromPowerBuilder,thefollowingcodesetsthevalueofthepointerSetValtotheintegervaluepassedinbyf_setprop,thenregistersthatvalueinthesessionwiththepropertynameprop_name:int*SetVal=newint;
if(mid==mid_SetProp)
{
*SetValue=ci->pArgs->GetAt(0)->GetInt();
session->SetProp(prop_name,SetVal);
}
Whenthef_getpropfunctioniscalled,thefollowingcodeusesGetProptosettheGetValuepointertopointtothevalueassociatedwithprop_name,andthensetsthereturnvalueto*GetValue:if(mid==mid_GetProp)
{
int*GetVal;
GetValue=(int*)session->GetProp(prop_name);
ci->returnValue->SetInt(*GetVal);
}
UsageSetPropenablesyoutouseavariablevaluethroughoutanIPBsessionwithoutusingaglobalvariable,whichissusceptibletonamespaceconflictswithothersessions.SetPropisoneofasetofthreefunctions:
UseSetProptoregisteranewvariablewiththesessionortochangethevalueofanexistingvariable.UseGetProptoaccessthevariable.UseRemoveProptoremovethevariablefromthelistofvariablesassociatedwiththesessionwhenitisnolongerneeded.
ThissetoffunctionsisparticularlyusefulforworkingwithmultiplethreadsofexecutioninEAServer.SupposeyouwanttothrowanexceptionfromwithinaPBNIextensionandtheexceptionitselfisalsodefinedbythePBNIextension.YoucalltheIPB_SessionNewObjectfunctiontocreateaninstanceoftheexception,causingthePBX_CreateNonVisualObjectfunctiontobecalled.Onewaytosetthevalueofthefieldsoftheexceptionbeforethefunctionreturnsinathread–safemanneristocreateanewobjectorstructuretoholdtheexceptioninformationbeforecallingNewObject.YoucancallSetProptostorethestructureortheobjectinthecurrentIPB_Session.WhenPBX_CreateNonVisualObjectiscalled,youcancallGetProptogetthestructureorobjecttoobtaintheexceptioninformation,thencall
RemoveProptoremovethedatayoustoredinthecurrentsession.
SeeAlsoGetProp|RemoveProp
IPB_Sessioninterface:SetSharedVarToNullmethod
DescriptionSetsthevalueofthespecifiedsharedvariabletonull.
SyntaxSetSharedVarToNull(pbgroupgroup,pbfieldfid)
Argument Description
group Thegrouptowhichthesharedvariablebelongs
fid ThefieldIDofthesharedvariable
ReturnValuesNone.
ExamplesThisexampleteststheIsSharedVarNullandSetSharedVarToNullfunctions:curGroup=session->GetCurrGroup();
cls=session->GetClass(myobj);
fid=session->GetSharedVarID(curGroup,"i_svar");
if(session->IsSharedVarNull(curGroup,fid))
session->SetIntSharedVar(curGroup,fid,1);
else
session->SetSharedVarToNull(curGroup,fid);
SeeAlsoGet<type>SharedVar|GetSharedVarID|GetSharedVarType|IsSharedVarArray
|IsSharedVarNull|IsSharedVarObject|Set<type>SharedVar
IPB_Sessioninterface:SetStringmethod
DescriptionFreesanexistingstringandassignsanewstringvaluetoitbyperformingadeepcopy.
SyntaxSetString(pbstringstring,LPCTSTRsrc)
Argument Description
string Avalidpbstringvariablewhosevalueistobereplaced
src Thestringtobeassignedtostring
ReturnValuesPBXRESULT.ReturnsPBX_OKforsuccessorPBX_E_INVALID_ARGUMENTifthenewstringvalueisinvalid;otherwise,returnsPBX_E_OUTOF_MEMORY.
ExamplesThisexampleusestheIPB_SessionSetStringmethodtosettheret_valstringtothereturnvalueinthePBCallInfostructure.ItalsousestheIPB_ValueSetPBStringmethodtosetvaluesinPBCallInfo:pbclasscls;
pbmethodIDmid;
PBCallInfo*ci=newPBCallInfo;
pbstringret_val;
LPCTSTRpStr;
cls=Session->GetClass(myobj);
if(isAny)
mid=Session->GetMethodID(cls,"uf_any_byvalue",
PBRT_FUNCTION,"AAAAA");
else
mid=Session->GetMethodID(cls,"uf_string_byvalue",
PBRT_FUNCTION,"SSSSS");
Session->InitCallInfo(cls,mid,ci);
ci->pArgs->GetAt(0)->SetPBString(s_low);
ci->pArgs->GetAt(1)->SetPBString(s_mid);
ci->pArgs->GetAt(2)->SetPBString(s_high);
pStr=Session->GetString(s_null);
if(pStr!=0)
{
if(strcmp(pStr,"null")==0)
ci->pArgs->GetAt(3)->SetToNull();
else
ci->pArgs->GetAt(3)->SetPBString(s_null);
}
Session->InvokeObjectFunction(myobj,mid,ci);
ret_val=Session->NewString("");
Session->SetPBString(ret_val,Session->GetString
(ci->returnValue->GetString()));
Session->FreeCallInfo(ci);
deleteci;
returnret_val;
UsageAdeepcopyisperformed.Theexistingvalueisdestroyedfirst,andthenthecontentsofthesrcargumentarecopiedintoanewvalue.
SeeAlsoNewString
IPB_Sessioninterface:SetTimemethod
DescriptionResetsthevalueofthespecifiedpbtimeobject.
SyntaxSetTime(pbtimetime,pbinthour,pbintminute,pbdoublesecond)
Argument Description
time Thepbtimeobjecttobereset
hour Anhourintherange0to23
minute Aminuteintherange0to59
second Asecondintherange0to59.999999
ReturnValuesPBX_RESULT.PBX_OKforsuccessorPBX_E_INVALID_ARGUMENTifthenewtimeisinvalid.
ExamplesThiscodeputsanewtimewiththevalue01:01:01intothetime_valpropertyofthepArgumentsarrayifthevalueinthePBCallInfostructureisnull.Otherwiseitsetstime_valtothetimeinthePBCallInfostructure:if(ci->pArgs->GetAt(i)->IsNull())
{
pArguments[i].time_val=Session->NewTime();
Session->SetTime(pArguments[i].time_val,1,1,1);
//Time:01:01:01
}
else
{
pArguments[i].time_val=
ci->pArgs->GetAt(i)->GetTime();
}
UsageIftheparametersareinvalid,thetimeisresetto0:0:0.0.
SeeAlsoNewTime|SplitTime
IPB_Sessioninterface:SetValuemethod
DescriptionSetsthevalueofoneIPB_ValueobjecttothevalueofanotherIPB_Valueobject.
SyntaxSetValue(IPB_Value*dest,IPB_Value*src)
Argument Description
dest Thevaluetobereplaced
src Thevaluetowhichdestistobechanged
ReturnValuesNone.
ExamplesThesestatementssetthereturnvalueinthePBCallInfostructurecitothevalueIPBValue_ret,thenreleasetheIBPValue_retstructure:Session->SetValue(ci->returnValue,IPBValue_ret);
Session->ReleaseValue(IPBValue_ret);
UsageUnliketheIPB_ValueSet<type>methods,theSetValuemethoddoesnotverifythatthedatatypeofthereplacementvaluematchesthedatatypeoftheoriginalvalue.Theoriginalvalueisfreedandanewvalueisclonedfromthesrcvalue.UsethismethodifyouwanttoswaptwodifferentIPB_Valueobjectsthathavedifferenttypes.
SeeAlsoAcquireValue,ReleaseValue
IPB_Sessioninterface:SplitDatemethod
DescriptionSplitsthespecifiedpbdateobjectintoayear,month,andday.
SyntaxSplitDate(pbdatedate,pbint*year,pbint*month,pbint*day)
Argument Description
date Thepbdateobjecttobesplit
year Ayearintherange1000to3000
month Amonthintherange1to12
day Adayintherange1to31
ReturnValuesPBX_RESULT.PBX_OKforsuccess.
ExamplesThisstatementsplitsthedateinthefirstvalueinthePBCallInfostructure:Session->SplitDate(ci->pArgs->GetAt(0)->
GetDate(),&yy,&mm,&dd);
SeeAlsoNewDate,SetDate,SplitDateTime
IPB_Sessioninterface:SplitDateTimemethod
DescriptionSplitsthespecifiedpbdatetimeobjectintoayear,month,day,hour,minute,andsecond.
SyntaxSplitDateTime(pbdatetimedt,pbint*year,pbint*month,pbint*day,pbint*
Argument Description
dt Thepbdatetimeobjecttobesplit
year Ayearintherange1000to3000
month Amonthintherange1to12
day Adayintherange1to31
hour Anhourintherange0to23
minute Aminuteintherange0to59
second Asecondintherange0to59.999999
ReturnValuesPBX_RESULT.PBX_OKforsuccess.
SeeAlsoNewDateTime,SetDateTime,SplitDate,SplitTime
IPB_Sessioninterface:SplitTimemethod
DescriptionSplitsthespecifiedtimeobjectintoanhour,minute,andsecond.
SyntaxSplitTime(pbtimetime,pbint*hour,pbint*minute,pbdouble*second)
Argument Description
time Thepbtimeobjecttobesplit
hour Anhourintherange0to23
minute Aminuteintherange0to59
second Asecondintherange0to59.999999
ReturnValuesPBX_RESULT.PBX_OKforsuccess.
ExamplesThesestatementssplitatimeintohours,minutes,andseconds,andthenusetheresultingvaluestosetthevalueofanewtimeobject:Session->SplitTime(ci.returnValue->GetTime(),&hh,
&mm,&ss);
ret_val=Session->NewTime();
Session->SetTime(ret_val,hh,mm,ss);
SeeAlsoNewTime|SetTime
IPB_Sessioninterface:ThrowExceptionmethod
DescriptionThrowsaPowerBuilderexceptionorinheritedexception,andreplacestheexistingexceptionifthereisone.
SyntaxThrowException(pbobjectex)
Argument Description
ex Theexceptiontobethrown.TheexceptionmustfirstbecreatedwithNewObject.
ReturnValuesNone.
ExamplesThiscodecreatesanewexceptionobjectintheclassuser_exception_pspp,invokesitsSetMessagefunction,andthrowstheexception:pbclasscls;
pbmethodIDmid;
pbobjectex;
pbgroupgroup;
PBCallInfo*ci=newPBCallInfo;
//Throwexception
group=session->FindGroup("user_exception_pspp",
pbgroup_userobject);
if(group==NULL)
return;
cls=session->FindClass(group,"user_exception_pspp");
if(group==NULL)
return;
ex=session->NewObject(cls);
mid=session->GetMethodID(cls,
"setmessage",PBRT_FUNCTION,"QS");
session->InitCallInfo(cls,mid,ci);
ci->pArgs[0].SetPBString(session,"Testexception");
session->InvokeObjectFunction(ex,mid,ci);
session->ThrowException(ex);
if(!ThrowToPB)
session->ClearException();
session->FreeCallInfo(ci);
deleteci;
return;
SeeAlsoClearException|GetException|HasExceptionThrown
IPB_Sessioninterface:TriggerEventmethod
DescriptionTriggersaPowerBuilderevent.
SyntaxTriggerEvent(pbobjectobj,pbmethodIDmid,PBCallInfo*ci)
Argument Description
obj Thepbobjectcontainingthemethod
mid ThepbMethodIDreturnedbyGetMethodID
ci ApointertoapreallocatedPBCallInfostructure
ReturnValuesPBXRESULT.ReturnsPBX_OKforsuccess,oroneofthefollowingforfailure:
PBX_E_INVALID_ARGUMENTPBX_E_INVOKE_METHOD_INACCESSABLEPBX_E_INVOKE_WRONG_NUM_ARGSPBX_E_INVOKE_REFARG_ERRORPBX_E_INVOKE_METHOD_AMBIGUOUSPBX_E_INVOKE_FAILURE
ExamplesThiscodetriggerstheclickedeventonaDataWindowobject:cls=session->GetClass(dwobj);
mid=session->GetMethodID
(cls,"clicked",PBRT_EVENT,"LIILCdwobject.");
session->InitCallInfo(cls,mid,ci);
session->TriggerEvent(dwobj,mid,ci);
...
SeeAlsoGetClass|GetMethodID
IPB_Sessioninterface:UpdateFieldmethod
DescriptionRefreshesavisualpropertyofaPowerBuilderobject.
SyntaxUpdateField(pbobjectobj,pbfieldIDfid)
Argument Description
obj Thepbobjectwhoseuserinterfacepropertyneedstobechanged
fid ThefieldIDoftheobject
ReturnValuesPBXRESULT.Returnssuccessorfailure.
ExamplesThisfunctionchangesthetitleofaDataWindowcontrol:voidCallBack::f_newtitle(IPB_Session*session,pbstringstr_val,pbobjectdwobj)
{
pbclasscls;
pbfieldIDfid;
cls=session->GetClass(dwobj);
fid=session->GetFieldID(cls,"title");
if(fid==kUndefinedFieldID)
return;
session->SetPBStringField(dwobj,fid,str_val);
session->UpdateField(dwobj,fid);
return;
}
UsageWhenyouchangeanyvisualpropertyofaPowerBuilderobjectbycalling
Set<type>fieldfunctions,thepropertyischangedbutthepropertyisnotrefreshedinthegraphicaluserinterface.UpdateFieldrefreshesthevisualpropertiesofPowerBuilderobjects.YoumustcallthisfunctionexplicitlywhenchanginganyvisualpropertywiththeSet<type>fieldfunctions.
SeeAlsoSet<type>Field
IPB_Valueinterface:Get<type>method
DescriptionAsetofdatatype-specificmethodsthatreturnapointertothedatainIPB_Value.
SyntaxGetArray()
GetBlob()
GetBool()
GetByte()
GetChar()
GetDate()
GetDateTime()
GetDecimal()
GetDouble()
GetInt()
GetLong()
GetLongLong()
GetObject()
GetReal()
GetString()
GetTime()
GetUint()
GetUlong()
ReturnValuesApredefinedPBNIdatatypethatcorrespondstothePowerBuilderdatatypeinthemethodname.
ExamplesThisstatementgetsthedateinthefirstvalueinthePBCallInfostructure
andsplitsitintoyear,month,andday:Session->SplitDate(ci->pArgs->GetAt(0)->
GetDate(),&yy,&mm,&dd);
UsageIfIPB_Valuecontainsanullvalue,orifyouaretryingtogetaspecificdatatypefromanIPB_Valueinstanceofanotherdatatype,thedataretrievedisundetermined.Ifthedatatypeisstring,blob,decimal,time,date,datetime,array,orobject,thereturnvaluepointstothesameaddresspointedtobyIPB_Value.Asaresult,changingeitherthevariablethatholdsthereturnvalueorthevalueoftheIPB_Valueinstanceaffectstheother.
SeeAlsoSet<type>
IPB_Valueinterface:GetClassmethod
DescriptionReturnstheclasshandleofaPowerBuilderobject.
SyntaxGetClass()
ReturnValuespbclassornullonerror.
Examplespbclassclz=ci->pArgs->GetAt(i)->GetClass();
SeeAlsoGet<type>|GetType|Set<type>
IPB_Valueinterface:GetTypemethod
DescriptionReturnsthedatatypeofasingledataitemorarray.
SyntaxGetType()
ReturnValuespbuint
ExamplesArgsType=ci->pArgs->GetAt(i)->GetType();
switch(ArgsType)
{
casepbvalue_int:
if(ci->pArgs->GetAt(i)->IsNull())
pArguments[i].int_val=1;
else
pArguments[i].int_val=
ci->pArgs->GetAt(i)->GetInt();
break;
...
UsageIftheIPB_Valueinstancecontainsanobjectorstructure,GetTypereturnstheclassIDofthedata.Otherwise,itreturnsasimpledatatypedefinedinthelistofpbvalue_typeenumeratedtypes.
SeeAlsoGet<type>|GetClass|Set<type>
IPB_Valueinterface:IsArraymethod
DescriptionReturnstrueiftheIPB_Valueinstancecontainsanarray;otherwise,returnsfalse.
SyntaxIsArray()
ReturnValuespbboolean
ExamplesThisexampletestswhetheranIPB_Valueinstanceisanarraybeforeobtainingthearray:if(ci->pArgs->GetAt(i)->IsArray())
{
pArguments[i].array_val=
ci->pArgs->GetAt(i)->GetArray();
continue;
}
SeeAlsoIsByRef|IsEnum|IsObject
IPB_Valueinterface:IsByRefmethod
DescriptionReturnstrueiftheIPB_Valueinstancecontainsabyreferenceargument;otherwiseitreturnsfalse.
SyntaxIsByRef()
ReturnValuespbboolean
ExamplesThisexampleshowshowyouwoulduseIsByReftotestwhetheranargumentisobtainedbyreference:if(ci->pArgs->GetAt(i)->IsByRef())
...
SeeAlsoIsArray|IsEnum|IsObject
IPB_Valueinterface:IsEnummethod
DescriptionReturnstrueiftheIPB_Valueinstancecontainsanenumeratedvalue;otherwiseitreturnsfalse.
SyntaxIsEnum()
ReturnValuespbboolean
SeeAlsoGetEnumItemName|GetEnumItemValue
IPB_Valueinterface:IsNullmethod
DescriptionReturnstrueiftheIPB_Valueinstancecontainsanullvalue;otherwise,itreturnsfalse.
SyntaxIsNull()
ReturnValuespbboolean
ExamplesThisexampletestswhetheranIPB_Valueinstancecontainsanullvaluebeforeattemptingtoobtainitsvalue:if(ci->pArgs->GetAt(i)->IsObject())
{
if(ci->pArgs->GetAt(i)->IsNull())
pArguments[i].obj_val=0;
else
pArguments[i].obj_val=
ci->pArgs->GetAt(i)->GetObject();
continue;
}
...
SeeAlsoIsArray|IsByRef|IsObject|SetToNull
IPB_Valueinterface:IsObjectmethod
DescriptionReturnstrueiftheIPB_Valueinstancecontainsanobjectorobjectarray;otherwiseitreturnsfalse.
SyntaxIsObject()
ReturnValuespbboolean
ExamplesThisexampletestswhetheranIPB_Valueinstancecontainsanobjectbeforeattemptingtoobtaintheobject:if(ci->pArgs->GetAt(i)->IsObject())
{
if(ci->pArgs->GetAt(i)->IsNull())
pArguments[i].obj_val=0;
else
pArguments[i].obj_val=
ci->pArgs->GetAt(i)->GetObject();
continue;
}
...
SeeAlsoIsArray|IsByRef|IsEnum
IPB_Valueinterface:Set<type>method
DescriptionSetofdatatype-specificmethodsthatsetthevalueoftheIPB_Valueinstance.
SyntaxSetArray(pbarrayarray)
SetBlob(pbblobblob)
SetBool(pbbooleanboolean)
SetByte(pbbytebyte)
SetChar(pbcharchar)
SetDate(pbdatedate)
SetDateTime(pbdatetimedatetime)
SetDecimal(pbdecimaldec)
SetDouble(pbdoubledouble)
SetInt(pbintint)
SetLong(pblonglong)
SetLongLong(pblonglonglonglong)
SetObject(pbobjectobject)
SetPBString(pbstringstring)
SetReal(pbrealreal)
SetString(LPCTSTRstring)
SetTime(pbtimetime)
SetUint(pbuintuint)
SetUlong(pbulongulong)
ReturnValuesPBXRESULT.
ExamplesThisexampleusestheIPB_ValueSetPBStringmethodtosetvaluesin
PBCallInfo.ItalsousestheIPB_SessionSetStringmethodtosettheret_valstringtothereturnvalueinthePBCallInfostructure:pbclasscls;
pbmethodIDmid;
PBCallInfo*ci=newPBCallInfo;
pbstringret_val;
LPCTSTRpStr;
cls=Session->GetClass(myobj);
if(isAny)
mid=Session->GetMethodID(cls,"uf_any_byvalue",
PBRT_FUNCTION,"AAAAA");
else
mid=Session->GetMethodID(cls,"uf_string_byvalue",
PBRT_FUNCTION,"SSSSS");
Session->InitCallInfo(cls,mid,ci);
//CallIPB_ValueSetPBStringmethod
ci->pArgs->GetAt(0)->SetPBString(s_low);
ci->pArgs->GetAt(1)->SetPBString(s_mid);
ci->pArgs->GetAt(2)->SetPBString(s_high);
pStr=Session->GetString(s_null);
if(pStr!=0)
{
if(strcmp(pStr,"null")==0)
ci->pArgs->GetAt(3)->SetToNull();
else
ci->pArgs->GetAt(3)->SetPBString(s_null);
}
Session->InvokeObjectFunction(myobj,mid,ci);
ret_val=Session->NewString("");
//CallIPB_SessionSetStringmethod
Session->SetString(ret_val,Session->GetString
(ci->returnValue->GetString()));
Session->FreeCallInfo(ci);
deleteci;
returnret_val;
UsageThesemethodsautomaticallysetthevalueofIPB_Valuetonotnullandreturnanerrorifthedatatypetobesetdoesnotmatchtheexistingdatatype.TheerrorcodeisPBX_E_MISMATCHED_DATA_TYPE.Ifthevalueisaread-onlyargument,itreturnstheerror
PBX_E_READONLY_ARGS.Ifthedatatypeisstringorblob,adeepcopyisperformed.Theexistingvalueisdestroyedfirst,andthenthecontentsoftheargumentarecopiedintoanewvalue.
SeeAlsoGet<type>
IPB_Valueinterface:SetToNullmethod
DescriptionSetsthedatacontainedintheIPB_Valueinstancetonullsothedatacanbereset.
SyntaxSetToNull()
ReturnValuesPBXRESULT.Ifthevalueisaread-onlyargument,theerrorPBX_E_READONLY_ARGSisreturned.
ExamplesThisexampleshowstheuseofSetToNullwhenanullblobvalueisreturned:casepbvalue_blob:
pStr=(LPCTSTR)Session->GetBlob(retVal.blob_val);
if(strncmp(pStr,"null",4)==0)
ci->returnValue->SetToNull();
else
ci->returnValue->SetBlob(retVal.blob_val);
break;
...
SeeAlsoIsEnum
IPB_VMinterface:CreateSessionmethod
DescriptionCreatesanIPB_SessionobjectthatcanbeusedtocallPowerBuilderfunctions.
SyntaxCreateSession(LPCTSTRapplicationName,LPCTSTR*libraryList,pbuint
Argument Description
applicationNameThenameofthecurrentapplicationobjectinlowercase
libraryList ThelibrarylistofthePowerBuilderapplicationthatcontainstheobjectsandfunctionstobecalled
numLibs Thenumberoflibrariesinthelibrarylist
session ApointertoIPB_Session*,whichwillreturnthecurrentIPB_Sessionpointerafterthecall
ReturnValuesPBXRESULT.PBX_OKforsuccess.
ExamplesThisexamplecreatesanIPB_Sessionwiththesimplelibrarylistmydemo.pbl:IPB_Session*session;
IPB_VM*vm=NULL;
fstreamout;
ifstreamin;
PBXRESULTret;
HINSTANCEhinst=LoadLibrary("pbvm125.dll");
if(hinst==NULL)return0;
out<<"LoadedPowerBuilderVMsuccessfully!"<<endl;
P_PB_GetVMgetvm=(P_PB_GetVM)GetProcAddress
(hinst,"PB_GetVM");
if(getvm==NULL)return0;
getvm(&vm);
if(vm==NULL)return0;
staticconstchar*liblist[]=
{
"mydemo.pbl"
};
ret=vm->CreateSession("mydemo",liblist,1,&session);
if(ret!=PBX_OK)
{
out<<"Createsessionfailed."<<endl;
return0;
}
out<<"Createsessionsucceeded!"<<endl;
SeeAlsoRunApplication
IPB_VMinterface:RunApplicationmethod
DescriptionRunsthespecifiedapplication.
SyntaxRunApplication(LPCTSTRapplicationName,LPCTSTR*libraryList,pbuint
Argument Description
applicationNameThenameoftheapplicationobjecttoberun,inlowercase
libraryList Thelibrarylistoftheapplication
numLibs Thenumberoflibrariesinthelibrarylist
commandLine Parameterstobepassedtotheapplicationobject
session ApointertoIPB_Session*,whichwillreturnthecurrentIPB_Sessionpointerafterthecall
ReturnValuesPBXRESULT.PBX_OKforsuccess.
ExamplesThiscodefragmentloadsthePowerBuilderVMandrunsanapplicationcalledrunappthatusesonelibrary,runapp.pbd.Itpassesinacommandlinewithtwoarguments:LRESULTCALLBACKWndProc(HWNDhWnd,UINTmessage,WPARAMwParam,LPARAMlParam)
{
LPCTSTRszHello="Helloworld";
//Providecommandlineparameters(employeeids)
//tobepassedtothePowerBuilderapplication
LPCTSTRszcommandline="102110";
intwmId,wmEvent,ret;
PAINTSTRUCTps;
HDChdc;
switch(message)
{
caseWM_CREATE:
{
hPBVMInst=::LoadLibrary("pbvm125.dll");
P_PB_GetVMgetvm=(P_PB_GetVM)
GetProcAddress(hPBVMInst,"PB_GetVM");
IPB_VM*vm=NULL;
getvm(&vm);
staticconstchar*liblist[]=
{"runapp.pbd"};
vm->RunApplication("runapp",liblist,1,
szcommandline,&session);
break;
}
SeeAlsoCreateSession
IPBX_Marshalerinterface:Destroymethod
DescriptionUsetheDestroymethodtodestroyinstancesofobjectsinheritedfromtheIPBX_Marshalerstructure.
SyntaxDestroy()
ReturnValuesNone.
ExamplesThiscodedestroysthecurrentinstanceoftheSampleMarshalerstructure:voidSampleMarshaler::Destroy()
{
deletethis;
}
UsageYoumustimplementthismethodinthemarshalernativeclassaftercreatinganinstanceofamarshalerstructureandinvokingremotemethods.
SeeAlsoGetModuleHandle|InvokeRemoteMethod
IPBX_Marshalerinterface:GetModuleHandlemethod
DescriptionReturnsthehandleofthePBXthatcontainsthenativeclass.ThismethodisrequiredtoallowthePowerBuilderVMtodeterminewhichPBXscanbeunloaded.
SyntaxGetModuleHandle()
ReturnValuespbulong
ExamplesThiscodeintheimplementationofamarshalerclassreturnsthehandleofthePBX:externpbulongthisModuleHandle;
pbulongSampleMarshaler::GetModuleHandle()
{
returnthisModuleHandle;
}
Thehandleissetinthemainmodule:pbulongthisModuleHandle=0;
BOOLAPIENTRYDllMain(HANDLEhModule,
DWORDul_reason_for_call,
LPVOIDlpReserved
)
{
thisModuleHandle=(pbulong)hModule;
switch(ul_reason_for_call)
{
caseDLL_PROCESS_ATTACH:
caseDLL_THREAD_ATTACH:
caseDLL_THREAD_DETACH:
caseDLL_PROCESS_DETACH:
break;
}
returnTRUE;
}
UsageYoumustimplementthismethodinthemarshalernativeclass.
SeeAlsoDestroy|InvokeRemoteMethod
IPBX_Marshalerinterface:InvokeRemoteMethodmethod
DescriptionUsedinPowerBuildermarshalernativeclassestocallremotemethods.
SyntaxInvokeRemoteMethod(IPB_Session*session,pbproxyobjectobj,LPCTSTR
Argument Description
session ThisIPBsession
obj Theproxyobjectfortheremoteobject
methodDescAnarbitrarystringstoredasanaliasnamefortheremotemethodintheproxy,forexample:functionintfoo(inta)alias"ThisisamethodinremoteBizTalk"
ci Theparametersandreturnvaluesettingforthecall
ReturnValuesPBXRESULT.PBX_OKifthecallsucceeded.
ExamplesThisexampleshowsaheaderfileforasamplemarshalerclass:#include"sampleinclude.h"
#include<pbext.h>
classSampleMarshaler:publicIPBX_Marshaler
{
private:
stringd_mystring;
longd_mylong;
private:
voidmyMethod(stringarg1);
public:
SampleMarshaler(
stringmyString,
longmylong
);
~SampleMarshaler();
virtualPBXRESULTInvokeRemoteMethod
(
IPB_Session*session,
pbproxyObjectobj,
LPCTSTRmethodDesc,
PBCallInfo*ci
);
virtualpbulongGetModuleHandle();
virtualvoidDestroy();};
TheassociatedC++implementationfilecontainscodelikethis:PBXRESULTSampleMarshaler::InvokeRemoteMethod
(
IPB_Session*session,
pbproxyObjectobj,
LPCTSTRmethodDesc,
PBCallInfo*ci
)
{
//methodinvocation
}
UsageYoumustimplementthismethodinthemarshalernativeclass.
SeeAlsoDestroy|GetModuleHandle
IPBX_UserObjectinterface:Destroymethod
DescriptionDestroysthecurrentinstanceofaPowerBuildernativeclassthatinheritsfromIPBX_UserObject.
SyntaxDestroy()
ReturnValuesNone.
ExamplesThisexampleshowshowyouwouldcallDestroyfortheclassMyPBNIClass:voidMyPBNIClass::Destroy()
{
deletethis;
}
UsageYoumustimplementthismethodinthenativeclassaftercreatinganinstanceoftheclassandinvokingremotemethods.
SeeAlsoInvoke
IPBX_UserObjectinterface:Invokemethod
DescriptionCallsmethodsinPowerBuildernativeclasses.
SyntaxInvoke(IPB_Session*session,pbobjectobj,pbmethodIDmid,PBCallInfo*
Argument Description
session ThisIPBsession
obj ThePowerBuilderextensionobjecttobeinvoked
mid ThepbMethodIDreturnedbyGetMethodID
ci Theparametersandreturnvaluesettingforthecall
ReturnValuesPBXRESULT.PBX_OKforsuccess.
ExamplesInthisexample,themethodinvokeddependsonthevalue(0,1,or2)ofthemethodIDreturnedfromtheGetMethodIDmethod:PBXRESULTPBNIExt::Invoke
(
IPB_Session*session,
pbobjectobj,
pbmethodIDmid,
PBCallInfo*ci
)
{
PBXRESULTresult=PBX_OK;
switch(mid)
{
casemFuncA:
result=FuncA(session,obj,ci);
break;
casemFuncB:
result=FuncB(session,obj,ci);
break;
casemFuncC:
result=FuncC(session,obj,ci);
break;
default:
result=PBX_E_INVOKE_FAILURE;
break;
}
returnPBX_OK;
}
SeeAlsoGetMethodID
IPBX_VisualObjectinterface:CreateControlmethod
DescriptionCreatesawindowcontrolandreturnsitshandletothePowerBuilderVM.
SyntaxCreateControl(DWORDdwExStyle,LPCTSTRlpWindowName,DWORDdwStyle,int
Argument Description
dwExStyle Theextendedwindowstyle
lpWindowNameThewindowname
dwStyle Thewindowstyle
x Thehorizontalpositionofthewindow
y Theverticalpositionofthewindow
nWidth Thewindow'swidth
nHeight Thewindow'sheight
hWndParent Thehandleoftheparentorownerwindow
hInstance Thehandleoftheapplicationinstance
ReturnValuesHWND.
ExamplesThisispartofavisualextensionexampleavailableontheSybaseWebsite:LPCTSTRCVisualExt::GetWindowClassName()
{
returns_className;
}
HWNDCVisualExt::CreateControl
(
DWORDdwExStyle,//extendedwindowstyle
LPCTSTRlpWindowName,//windowname
DWORDdwStyle,//windowstyle
intx,//horizontalpositionofwindow
inty,//verticalpositionofwindow
intnWidth,//windowwidth
intnHeight,//windowheight
HWNDhWndParent,//handletoparentorownerwindow
HINSTANCEhInstance//handletoapplicationinstance
)
{
d_hwnd=CreateWindowEx(dwExStyle,s_className,
lpWindowName,dwStyle,x,y,nWidth,nHeight,
hWndParent,NULL,hInstance,NULL);
::SetWindowLong(d_hwnd,GWL_USERDATA,(LONG)this);
returnd_hwnd;
}
UsageThewindowmustberegisteredbeforeyoucallCreateControl.
SeeAlsoGetEventID|GetWindowClassName
IPBX_VisualObjectinterface:GetEventIDmethod
DescriptionReturnstheidentifierofaneventwhenthewindow'sparentisnotifiedthattheeventoccurred.
SyntaxGetEventID(HWNDhWnd,uintiMsg,WPARAMwParam,LPARAMlParam)
Argument Description
hWnd Thehandleoftheparentwindow.
iMsg Themessagesenttotheparent.
wParam
Thewordparameterofthemessage.ForWM_COMMAND,thehigh-orderwordspecifies:
Thenotificationcodeifthemessageisfromacontrol1ifthemessageisfromanaccelerator0ifthemessageisfromamenu.
Thelow-orderwordspecifiestheidentifierofthecontrol,accelerator,ormenu.ForWM_NOTIFY,thisparametercontainstheidentifierofthecontrolsendingthemessage.
lParam
Thelongparameterofthemessage.ForWM_COMMAND,thisparametercontainsthehandleofthecontrolsendingthemessageifthemessageisfromacontrol.Otherwise,thisparameterisnull.ForWM_NOTIFY,thisparametercontainsapointertoastructure.
ReturnValuesInteger.
ExamplesInthisexample,theGetEventIDfunctionreturnstheidentifierPB_BNCLICKEDifaWM_COMMANDmessagewiththenotificationcodeBN_CLICKEDwassent.ItreturnstheidentifierPB_ENCHANGEifaWM_NOTIFYmessagewassent;otherwiseitreturnsPB_NULL.TCHARCVisualExt::s_className[]="PBVisualExt";
LPCTSTRCVisualExt::GetWindowClassName()
{
returns_className;
}
HWNDCVisualExt::CreateControl
(
DWORDdwExStyle,//extendedwindowstyle
LPCTSTRlpWindowName,//windowname
DWORDdwStyle,//windowstyle
intx,//horizontalpositionofwindow
inty,//verticalpositionofwindow
intnWidth,//windowwidth
intnHeight,//windowheight
HWNDhWndParent,//handleofparentorownerwindow
HINSTANCEhInstance//handleofapplicationinstance
)
{
d_hwnd=CreateWindowEx(dwExStyle,s_className,
lpWindowName,dwStyle,x,y,nWidth,nHeight,
hWndParent,NULL,hInstance,NULL);
::SetWindowLong(d_hwnd,GWL_USERDATA,(LONG)this);
returnd_hwnd;
}
intCVisualExt::GetEventID(
HWNDhWnd,/*Handleofparentwindow*/
UINTiMsg,/*Messagesenttoparentwindow*/
WPARAMwParam,/*Wordparameterofmessage*/
LPARAMlParam/*Longparameterofmessage*/
)
{
if(iMsg==WM_COMMAND)
{
if((HWND)lParam==d_hwnd)
{
switch(HIWORD(wParam))
{
caseBN_CLICKED:
returnPB_BNCLICKED;
break;
}
}
}
if(iMsg==WM_NOTIFY)
{
returnPB_ENCHANGE;
}
returnPB_NULL;
}
UsageThisfunctionisusedtoprocessWindowsmessages,suchasWM_COMMANDandWM_NOTIFY,thataresenttotheparentofanobjectandnottotheobjectitself.Suchmessagescannotbecaughtinthevisualextension'swindowprocedure.ThePBVMcallsGetEventIDtoprocessthesemessages.IfthemessageismappedtoaPowerBuilderevent,GetEventIDreturnstheevent'sidentifier,forexamplePB_BNCLICKED,andtheeventisfiredautomatically.PowerBuildereventtokenidentifiersaremappedtounsignedintegervaluesinthepbevtid.hheaderfile.Theidentifiersinpbevtid.hareassociatedwithPowerBuildereventtokennames.Forexample,theidentifierPB_BNCLICKEDisassociatedwiththetokennamepbm_bnclicked.Ifthemessageisnotmappedtoanevent,GetEventIDreturnsthevaluePB_NULLandthemessageisdiscarded.
SeeAlsoCreateControl|GetWindowClassName
IPBX_VisualObjectinterface:GetWindowClassNamemethod
DescriptionReturnsthenameofthewindow.
SyntaxGetWindowClassName()
ReturnValuesLPCTSTR.
ExamplesThestringreturnedbyGetWindowClassNameispassedasanargumenttotheCreateControlmethod:LPCTSTRCVisualExt::GetWindowClassName()
{
returns_className;
}
UsageThewindowmustberegisteredbeforeyoucallGetWindowClassName.
SeeAlsoCreateControl|GetEventID
PBArrayAccessortemplateclass:GetAtmethod
DescriptionObtainsthearrayitematthespecifieddimension.
SyntaxGetAt(pblongdim[])
ReturnValuesValueType(definedinpbtraits.h).
Argument Description
dim Thedimensionofthearrayitemtobeobtained
ExamplesSeeSetAt.
SeeAlsoSetAt
PBArrayAccessortemplateclass:IsNullmethod
DescriptionReturnstrueifthearrayitemcontainsanullvalue,otherwisereturnsfalse.
SyntaxIsNull(pblongdim[])
Argument Description
dim Thedimensionofthearrayitemtobetested
ReturnValuespbboolean.
SeeAlsoGetAt,SetAt,SetToNull|
PBArrayAccessortemplateclass:SetAtmethod
DescriptionSetsthearrayitematthespecifieddimension.
SyntaxForarraysofaspecifiedValueType:SetAt(pblongdim[],ValueTypev)
Forstringarrays:SetAt(pblongdim[],LPCTSTRstring)
SetAt(pblongdim[],pbstringstring)
Argument Description
dim Thedimensionofthearrayitemtobeset
v AValueTypedefinedinpbtraits.h
string AstringoftypepbstringorLPCTSTR
ReturnValuesNone.
ExamplesThisexampleshowstheuseofGetAtandSetAtinarraysofatypespecifiedbyaValueType:template<typenameT,pbvalue_typeI>
voidArrayCreator<T,I>::f_unbounded_simple_array(
IPB_Session*session,
ifstreamin,
fstreamout,
LPCSTRdata_type)
{
pbarrayout_array;
inti;
pblongdim[4],itemcount1,itemcount2;
T*iarg,oarg;
in>>itemcount1;
iarg=newT[itemcount1];
//Createunboundedintegerarray
{
PBUnboundedArrayCreator<I>ac(session);
out_array=ac.GetArray();
PBArrayAccessor<I>aa(session,out_array);
for(i=0;i<itemcount1;i++)
in>>iarg[i];
for(i=0;i<itemcount1;i++)
{
dim[0]=i+1;
aa.SetAt(dim,iarg[i]);
}
itemcount2=session->GetArrayItemCount(out_array);
out<<"Thearrayitemcountis"<<itemcount2<<
endl;
for(i=0;i<itemcount2;i++)
{
dim[0]=i+1;
oarg=aa.GetAt(dim);
if(oarg!=iarg[i])
out<<"***ERROR"<<endl;
else
out<<oarg<<"";
}
}
delete[]iarg;
out<<endl;
return;
}
SeeAlsoGetAt
PBArrayAccessortemplateclass:SetToNullmethod
DescriptionSetsthevalueofthespecifiedarrayitemtonull.
SyntaxSetToNull(pblongdim[])
Argument Description
dim Thedimensionofthearrayitemtobeset
ReturnValuesNone.
SeeAlsoGetAt|IsNull|SetAt
PBBoundedArrayCreatortemplateclass:GetArraymethod
DescriptionObtainsanarraythathasbeencreated.
SyntaxGetArray()
ReturnValuespbarray.
ExamplesThisexamplesetsupanarray,readsinvalues,andthenobtainsthevaluesinthearray:LPCTSTR*ostr_a;
char**sp;
inti;
pbarrayout_array;
arrayBounds*bounds;
pbuintdim1,dim2,current_dim;
pblongitemcount1,itemcount2;
PBXRESULTret;
PBArrayInfo*ai;
pbstring*iarg,*oarg;
typedefPBBoundedArrayCreator<pbvalue_string>
BoundedStringArrayCreator;
in>>dim1;
//allocatememoryforpointerbounds
bounds=(arrayBounds*)malloc(dim1*sizeof
(PBArrayInfo::ArrayBound));
bounds=newarrayBounds[dim1];
//readinlowerboundandupperboundforeachdimension
//andcalculatethearrayitemcount
itemcount1=1;
for(i=0;i<dim1;i++)
{
in>>bounds[i].lowerBound>>bounds[i].upperBound;
itemcount1=itemcount1*
(bounds[i].upperBound-bounds[i].lowerBound+1);
}
sp=newchar*[itemcount1];
ostr_a=newLPCTSTR[itemcount1];
iarg=newpbstring[itemcount1];
//Readinarrayitems
for(i=0;i<itemcount1;i++)
{
sp[i]=newchar[20];
in>>sp[i];
iarg[i]=session->NewString(sp[i]);
}
//createboundedsimplearrayandsetiarg[i]toit
{
BoundedStringArrayCreatorac(session,dim1,bounds);
current_dim=1;
BoundedArrayItem<pbstring,pbvalue_string,
BoundedStringArrayCreator>::f_set_arrayitem
(session,ac,dim1,bounds,iarg,current_dim);
BoundedArrayItem<pbstring,pbvalue_string,
BoundedStringArrayCreator>::array_itemcount=0;
out_array=ac.GetArray();
}
SeeAlsoSetAt
PBBoundedArrayCreatortemplateclass:SetAtmethod
DescriptionSetsavalueorstringtothearrayitematthespecifieddimension.
SyntaxForarraysofaspecifiedValueType:SetAt(pblongdim[],ValueTypev)
Forstringarrays:SetAt(pblongdim[],LPCTSTRstring)
SetAt(pblongdim[],pbstringstring)
Argument Description
dim Thedimensionofthearrayitemtobeset
v AValueTypedefinedinpbtraits.h
string AstringoftypepbstringorLPCTSTR
ReturnValuesNone.
ExamplesThisexampleshowstheuseofSetAtinarraysofatypespecifiedbyaValueType://arguments:
//ac:classobjectofPBBoundedArrayCreatoror
//PBBoundedObjectArrayCreatortosetitemsinto
//dimensions:arraydimension,canbe1,2,3,...,n
//bounds:upperandlowerboundforeachdimension
//iarg:Ttypearraytostorethedatavalueset
//intoarraycreatorac
//current_dim:rememberwhichdimensionisloopedinto
template<typenameT,pbvalue_typeI,classC>
voidBoundedArrayItem<T,I,C>::f_set_arrayitem
(IPB_Session*session,C&ac,pblongdimensions,
arrayBounds*bounds,T*iarg,intcurrent_dim)
{
inti;
if(current_dim>dimensions)
return;
for(i=bounds[current_dim-1].lowerBound;
i<=bounds[current_dim-1].upperBound;i++)
{
if(current_dim==dimensions)
{
dim[current_dim-1]=i;
ac.SetAt(dim,iarg[array_itemcount]);
array_itemcount++;
}
else
{
dim[current_dim-1]=i;
BoundedArrayItem<T,I,C>::f_set_arrayitem
(session,ac,dimensions,bounds,iarg,
current_dim+1);
}
}
}
SeeAlsoGetArray
PBBoundedObjectArrayCreatorclass:GetArraymethod
DescriptionObtainsanarraythathasbeencreated.
SyntaxGetArray()
ReturnValuespbarray.
ExamplesThisexamplesetsthevaluesinanarrayandthenusesGetArraytoobtainthearray:PBBoundedObjectArrayCreator<pbvalue_string>
ac(session);
for(i=0;i<itemcount1;i++)
{
ac.SetAt(i+1,iarg[i]);
}
out_array=ac.GetArray();
SeeAlsoSetAt
PBBoundedObjectArrayCreatorclass:SetAtmethod
DescriptionSetsthearrayitematthespecifieddimension.
SyntaxForarraysofaspecifiedValueType:SetAt(pblongdim[],ValueTypev)
Forstringarrays:SetAt(pblongdim[],LPCTSTRstring)
SetAt(pblongdim[],pbstringstring)
Argument Description
dim Thedimensionofthearrayitemtobeset
v AValueTypedefinedinpbtraits.h
string AstringoftypepbstringorLPCTSTR
ReturnValuesNone.
ExamplesThismethodisincludedintheexampleforGetArray.
SeeAlsoGetArray
PBObjectArrayAccessorclass:GetAtmethod
DescriptionObtainsthearrayitematthespecifieddimension.
SyntaxGetAt(pblongdim[])
ReturnValuespbobject.
Argument Description
dim Thedimensionofthearrayitemtobeset
ExamplesThisexampleshowstheuseofGetAtinanobjectarray:PBObjectArrayAccessoraa(session,*array_val);
for(i=0;i<itemcount2;i++)
{
dim[0]=i+1;
oarg=aa.GetAt(dim);
cls=session->GetClass(oarg);
if(cls==NULL)
return;
fid=session->GetFieldID(cls,"text");
if(fid==0xffff)
return;
fid_pv=session->GetFieldAddress(oarg,fid);
mystr=fid_pv->GetString();
ostr_a[i]=session->GetString(mystr);
}
SeeAlsoSetAt
PBObjectArrayAccessorclass:SetAtmethod
DescriptionSetsthearrayitematthespecifieddimension.
SyntaxSetAt(pblongdim[],pbobjectobj)
Argument Description
dim Thedimensionofthearrayitemtobeset
obj Avalidobjecthandle
ReturnValuesNone.
ExamplesThisexampleshowstheuseofSetAtinanobjectarray:PBObjectArrayAccessoraa(session,*array_val);
for(i=0;i<itemcount1;i++)
{
cls=session->FindClass(group,sp[i]);
if(cls==NULL)
return;
iarg=session->NewObject(cls);
session->ReferenceObject(iarg);
dim[0]=i+1;
aa.SetAt(dim,iarg);
fid=session->GetFieldID(cls,"text");
if(fid==0xffff)
return;
fid_pv=session->GetFieldAddress(iarg,fid);
mystr=fid_pv->GetString();
istr_a[i]=session->GetString(mystr);
}
SeeAlsoGetAt
PBUnboundedArrayCreatortemplateclass:GetArraymethod
DescriptionObtainsanarraythathasbeencreated.
SyntaxGetArray()
ReturnValuespbarray.
ExamplesThisexamplesetsthevaluesinanarrayandthenusesGetArraytoobtainthearray:PBUnboundedArrayCreator<pbvalue_string>ac(session);
for(i=0;i<itemcount1;i++)
{
ac.SetAt(i+1,iarg[i]);
}
out_array=ac.GetArray();
SeeAlsoSetAt
PBUnboundedArrayCreatortemplateclass:SetAtmethod
DescriptionSetsthearrayitematthespecifiedposition.
SyntaxForarraysofaspecifiedValueType:SetAt(pblongpos,ValueTypev)
Forstringarrays:SetAt(pblongpos,LPCTSTRstring)
SetAt(pblongpos,pbstringstring)
Argument Description
pos Apblongidentifyingapositioninthearray
v AValueTypedefinedinpbtraits.h
string AstringoftypepbstringorLPCTSTR
ReturnValuesNone.
ExamplesThisexampleshowstheuseofSetAtinarraysofatypespecifiedbyaValueType:PBUnboundedArrayCreator<I>ac(session);
in>>iarg[i];
for(i=0;i<itemcount1;i++)
{
ac.SetAt(i+1,iarg[i]);
}
out_array=ac.GetArray();
SeeAlsoGetArray
PBUnboundedObjectArrayCreatorclass:GetArraymethod
DescriptionObtainsanarraythathasbeencreated.
SyntaxGetArray()
ReturnValuespbarray.
SeeAlsoSetAt
PBUnboundedObjectArrayCreatorclass:SetAtmethod
DescriptionSetsthearrayitematthespecifieddimension.
SyntaxForarraysofaspecifiedValueType:SetAt(pblongpos,ValueTypev)
Forstringarrays:SetAt(pblongpos,LPCTSTRstring)
SetAt(pblongpos,pbstringstring)
Argument Description
pos Apblongidentifyingapositioninthearray
v AValueTypedefinedinpbtraits.h
string AstringoftypepbstringorLPCTSTR
ReturnValuesNone.
SeeAlsoGetArray
Exportedmethods:PBX_CreateNonVisualObjectmethod
DescriptionCreatesanewinstanceofanonvisualPowerBuilderextensionobject.
SyntaxPBX_CreateNonVisualObject(IPB_Session*pbsession,pbobjectpbobj,LPCTSTR
Argument Description
pbsession ThisIPBsession
pbobj ThenameofapbobjectcorrespondingtothePowerBuilderextensionobjecttobecreated
xtraname ThenameofthePowerBuildernativeclassinlowercase
obj ThePowerBuilderextensionobjecttobecreated
ReturnValuesPBXRESULT.PBX_OKforsuccess.
ExamplesInthisexample,theextensioncontainsseveralclasses.Theobjectcreateddependsonthestringvalueoftheclassnamepassedin.PBXEXPORTPBXRESULTPBXCALLPBX_CreateNonVisualObject
(
IPB_Session*pbsession,
pbobjectpbobj,
LPCTSTRxtraName,
IPBX_NonVisualObject**obj
)
{
PBXRESULTresult=PBX_OK;
stringcn(className);
if(cn.compare("class_a")==0)
{
*obj=newclass_a(pbobj);
}
elseif(cn.compare("class_b")==0)
{
*obj=newclass_b(pbobj);
}
elseif(cn.compare("class_c")==0)
{
*obj=newclass_b(pbobj);
else
{
*obj=NULL;
result=PBX_E_NO_SUCH_CLASS;
}
returnPBX_OK;
};
UsageYoumustimplementthismethodineveryPowerBuilderextensionmodulethatcontainsnonvisualclasses.WhenyouusetheCREATEstatementinPowerScripttocreateanewPowerBuilderextensionobject,thePBVMcallsthismethod.
SeeAlsoPBX_GetDescription
Exportedmethods:PBX_CreateVisualObjectmethod
DescriptionCreatesanewinstanceofavisualPowerBuilderextensionobject.
SyntaxPBX_CreateVisualObject(IPB_Session*pbsession,pbobjectpbobj,LPCTSTR
Argument Description
pbsession ThisIPBsession
pbobj ThenameofapbobjectcorrespondingtothePowerBuilderextensionobjecttobecreated
xtraname ThenameofthePowerBuildernativeclassinlowercase
obj ThePowerBuilderextensionobjecttobecreated
ReturnValuesPBXRESULT.PBX_OKforsuccess.
ExamplesInthisexampletheextensioncontainsseveralclasses.Theobjectcreateddependsonthestringvalueoftheclassnamepassedin.PBXEXPORTPBXRESULTPBXCALLPBX_CreateVisualObject
(
IPB_Session*pbsession,
pbobjectpbobj,
LPCTSTRclassName,
IPBX_VisualObject**obj
)
{
PBXRESULTresult=PBX_OK;
stringcn(className);
if(cn.compare("visualext")==0)
{
*obj=newCVisualExt(pbsession,pbobj);
}
else
{
*obj=NULL;
result=PBX_FAIL;
}
returnPBX_OK;
};
UsageYoumustimplementthismethodineveryPowerBuilderextensionmodulethatcontainsvisualclasses.WhenyouuseavisualextensioninaPowerBuilderapplication,thePBVMcallsthismethod.
SeeAlsoPBX_GetDescription
Exportedmethods:PBX_DrawVisualObjectmethod
DescriptionDrawsavisualobjectinthePowerBuilderdevelopmentenvironment.
SyntaxPBX_DrawVisualObject(HDChDC,LPCTSTRclassName,constPBX_DrawItemStruct&
Argument Description
hDC Ahandletothedevicecontextoftheobject
classnameThenameofthevisualextensionobjecttobedrawn
property APBX_DrawItemStructstructurespecifyingthedisplaypropertiesoftheobject
ReturnValuesPBXRESULT.Thereturnvalueofthisfunctioniscurrentlyignored.
ExamplesThisisanextensionofasamplethatisavailableonthePowerBuilderCodeXchangeWebsite.Itdrawsarepresentationofalight-emittingdiode(LED)andusesMicrosoftFoundationClasses(MFC):PBXEXPORTPBXRESULTPBXCALLPBX_DrawVisualObject
(
HDChDC,
LPCTSTRxtraName,
constPBX_DrawItemStruct&property
)
{
//IfthisPBXisdynamicallylinkedagainsttheMFC
//DLLs,anyfunctionsexportedfromthisPBXthat
//callintoMFCmusthavetheAFX_MANAGE_STATEmacro
//addedattheverybeginningofthefunction.
AFX_MANAGE_STATE(AfxGetStaticModuleState());
//VariablestoholdtheLedcontrolandapointer
//toDeviceContext
CLed*myLed;
CDC*pDC;
//Thenamemustnotcontainuppercaseletters
if(strcmp(xtraName,"u_cpp_led")==0)
{
CRectrc(property.x,property.y,property.x+
property.width,property.y+property.height);
//CreateanewLED
myLed=newCLed();
//GetthehandlefromthehDC
pDC=CDC::FromHandle(hDC);
CWnd*pWnd=pDC->GetWindow();
//Createthewindow
myLed->Create(NULL,WS_CHILD|WS_VISIBLE|
SS_BITMAP,rc,pWnd);
//Functionthathandlesthebackground
//renderingofthecontrol
myLed->OnEraseBkgndIDE(pDC);
//DrawtheLEDindefaultmode(red,on,round)
myLed->DrawLed(pDC,0,0,0);
myLed->SetLed(0,0,0);
//done
deletemyLed;
}
returnPBX_OK;
}
UsageInavisualextension,exportthisfunctionifyouwantthevisualcontroltobedrawninthedevelopmentenvironment.Ifyoudonotexportthefunction,youneedtoruntheapplicationtoseetheappearanceofthevisualcontrol.
SeeAlsoPBX_CreateVisualObject
|PBX_DrawItemStructstructure
Exportedmethods:PBX_GetDescriptionmethod
DescriptionPassesadescriptionofalltheclassesandmethodsinthePowerBuilderextensionmoduletoPowerBuilder.
SyntaxPBX_GetDescription()
ReturnValuesLPCTSTRcontainingthedescriptionofthemodule.
ExamplesThefollowingextensionmodulecontainsthreeclasses:PBXEXPORTLPCTSTRPBXCALLPBX_GetDescription()
{
staticconstTCHARdesc[]={
"classclass_afromnonvisualobject\n"
"functionlongmeth1(stringclasspath)\n"
"functionstringmeth2()\n"
"endclass\n"
"classclass_bfromnonvisualobject\n"
"subroutinesbrt1()\n"
"subroutinesbrt2()\n"
"functionlongfunc1()\n"
"endclass\n"
"classclass_cfromnonvisualobject\n"
"endclass\n"
};
returndesc;
}
Thefollowingmodulecontainsavisualclassthathastwosubroutines(functionsthatdonotreturnvalues),twoeventsthatrequirethatWindowsmessagesbecapturedintheextension(onclickandondoubleclick),andoneeventthatmapsaWindowsmessagedirectlyto
aPowerBuilderevent(testmouse).Themodulealsocontainstwoglobalfunctions,funcaandfuncb.PBXEXPORTLPCTSTRPBXCALLPBX_GetDescription()
{
staticconstTCHARdesc[]={
"classvisualextfromuserobject\n"
"eventintonclick()\n"
"eventintondoubleclick()\n"
"subroutinesetcolor(intr,intg,intb)\n"
"subroutinesettext(stringtxt)\n"
"eventtestmousepbm_mousemove\n"
"endclass\n"
"globalfunctions\n"
"functionintfunca(inta,intb)\n"
"functionintfuncb(inta,intb)\n"
"endglobalfunctions\n"
};
returndesc;
}
UsageYoumustimplementthismethodineveryPowerBuilderextensionmodule.ThemethodisexportedfromthePowerBuilderextensionmoduleandisusedbyPowerBuildertodisplaytheprototypeofeachclass,function,andeventinthemodule.Thesyntaxofthedescriptionfollows:Multipleinstances
Asyntaxelementwithanasteriskindicatesthatmultipleinstancesofthatelementcanappearinadescription.Forexample,[Desc]*indicatesthatonedescriptioncancontainmultipleclasses,globalfunctions,andforwarddeclarations.Desc::=
class_desc|globalfunc_desc|forward_desc|[Desc]*
class_desc::=
classclassNamefromparentClassnewline
[methods_desc]*endclassnewline
globalfunc_desc:=
globalfunctionsnewLine[func_desc]*endglobalfunctions
forward_desc:=
forwardnewLine[forwardtype_desc]*endforward
forwardtype_desc:=
classclassNamefromparentClassnewline
className::=
aPowerBuildertoken(cannotduplicateanexistinggroupname)
parentClass::=
anyclassinheritedfromNonVisualObjectorUserObject
newline::=
anewlinecharacter
methods_desc::=
method_desc[methods_desc]*
method_desc::=
func_desc|sub_desc|event_desc
func_desc::=
functionreturnTypefuncName(args_desc)newline
returnType::=
pbType
pbType::=
anyPowerBuildertype|previousdeclaredPBNIclass
funcName::=
aPowerBuildertoken
args_desc::=
None|arg_desc,[args_desc]*
arg_desc::=
[ref|readonly]pbTypeargName[array_desc]
argName::=
aPowerBuildertoken
array_desc::=
arraydeclarationofPowerBuilder
sub_desc::=
subroutinesubName(args_desc)newline
event_desc::=
eventreturnTypeeventName(args_desc)newline
|eventeventNamepbevent_tokennewline
pbevent_token::=
string
Thissyntaxforevent_descallowsyoutomapaWindowsmessagedirectlytoaPowerBuilderevent:eventeventNamepbevent_tokennewline
Formoreinformation,see"Eventprocessinginvisualextensions".
SeeAlsoPBX_CreateNonVisualObject|PBX_CreateVisualObject|PBX_InvokeGlobalFunction
Exportedmethods:PBX_InvokeGlobalFunctionmethod
DescriptionContainstheimplementationofoneormoreglobalfunctionsusedinthePowerBuilderextensionmodule.
SyntaxPBX_InvokeGlobalFunction(IPB_Session*pbsession,LPCTSTRfunctionname
Argument Description
pbsession ThisIPBsession
functionnameThenameoftheglobalfunction
ci ApointertoapreallocatedPBCallInfostructurecontainingtheparametersandreturnvaluesettingforthefunction
ReturnValuesPBXRESULT.PBX_OKforsuccess.
ExamplesThisPBX_GetDescriptioncalldeclaresthreeglobalfunctions:bitAnd,bitOr,andbitXor:PBXEXPORTLPCTSTRPBXCALLPBX_GetDescription()
{
staticconstTCHARdesc[]={
"globalfunctions\n"
"functionintbitAnd(inta,intb)\n"
"functionintbitOr(inta,intb)\n"
"functionintbitXor(inta,intb)\n"
"endglobalfunctions\n"
};
returndesc;
}
ThePBX_InvokeGlobalFunctioncallcontainstheimplementationofthefunctions:PBXEXPORTPBXRESULTPBXCALLPBX_InvokeGlobalFunction
(
IPB_Session*pbsession,
LPCTSTRfunctionName,
PBCallInfo*ci
)
{
PBXRESULTpbrResult=PBX_OK;
intarg1=ci->pArgs->GetAt(0)->GetInt();
intarg2=ci->pArgs->GetAt(1)->GetInt();
if(stricmp(functionName,"bitand")==0)
{
ci->returnValue->SetInt(arg1&arg2);
}elseif(strcmp(functionName,"bitor")==0)
{
ci->returnValue->SetInt(arg1|arg2);
}elseif(strcmp(functionName,"bitxor")==0)
{
ci->returnValue->SetInt(arg1^arg2);
}else
{
returnPBX_FAIL;
}
returnpbrResult;
}
UsageUsethisfunctioninaPowerBuildernativeclassthatusesglobalfunctions.ThefunctionisexportedfromthePowerBuilderextensionmoduleandisusedtoidentifyglobalfunctionsincludedinthemodule.LikeglobalfunctionsinPowerScript,globalfunctionsinPowerBuilderextensionscannotbeoverloaded.
SeeAlsoPBX_GetDescription
Exportedmethods:PBX_Notifymethod
DescriptionUsedtoinitializeanduninitializeasession.
SyntaxPBXEXPORTPBXRESULTPBXCALLPBX_Notify(IPB_Session*pbsession,pbint
ReturnValuesPBXRESULT
ExamplesThissampleshowscodethatexportsPBX_NotifyanddisplaysamessageboxafterthePBXisloadedandbeforeitisunloaded:PBXEXPORTPBXRESULTPBXCALLPBX_Notify
(
IPB_Session*pbsession,
pbintreasonForCall
)
{
switch(reasonForCall)
{
casekAfterDllLoaded:
MessageBox(NULL,"AfterPBXloading","",
MB_OK);
break;
casekBeforeDllUnloaded:
MessageBox(NULL,"BeforePBXunloading","",
MB_OK);
break;
}
returnPBX_OK;
}
UsageIfPBX_NOTIFYisexported,thePBVMcallsPBX_NotifyimmediatelyafteranextensionPBXisloadedandjustbeforethePBXisunloaded.
Youcanusethisfunctiontoinitializeanduninitializeasession.Forexample,youcouldcreateasessionmanagerobject,andstoreitintheIPBsessionusingtheSetPropfunction.Later,youcoulduseGetProptoobtainthesessionobject.
MethodexportedbyPowerBuilderVM:PB_GetVMmethod
DescriptionPassestheIPB_VMinterfacetotheuser.
SyntaxPB_GetVM(IPB_VM**vm)
ExamplesThisexampleloadsthePowerBuilderVMandcallsthef_getrowcountfunctiononthenvo_dwcustomclassuserobject:#include<pbext.h>
#include<iostream.h>
typedefPBXEXPORTPBXRESULT(*P_PB_GetVM)(IPB_VM**vm);
classLibraryLoader
{
public:
LibraryLoader(LPCSTRlibname)
{
d_hinst=LoadLibrary(libname);
}
~LibraryLoader()
{
FreeLibrary(d_hinst);
}
operatorHINSTANCE()
{
returnd_hinst;
}
private:
HINSTANCEd_hinst;
};
intmain()
{
intint_rowcount;
PBXRESULTret;
LibraryLoaderloader("pbvm125.dll");
if((HINSTANCE)loader==NULL)return0;
P_PB_GetVMgetvm=(P_PB_GetVM)
GetProcAddress((HINSTANCE)loader,"PB_GetVM");
if(getvm==NULL)return0;
IPB_VM*vm=NULL;
getvm(&vm);
if(vm==NULL)return0;
staticconstchar*liblist[]=
{
"load_pbvm.pbl"
};
IPB_Session*session=NULL;
ret=vm->CreateSession
("load_pbvm",liblist,1,&session);
if(ret!=PBX_OK)
{
cout<<"Createsessionfailure!"<<endl;
return0;
}
return1;
}
UsageToloadthePowerBuilderVMandrunaPowerBuilderapplicationinathird–partyserverorapplication,youfirstcreateanIPB_VMobjectusingthePB_GetVMmethod.Then,createanIPB_SessionobjectwithinIPB_VM,usingtheapplication'snameandlibrarylistasarguments.
SeeAlsoCreateSession
PBNIToolReference
AboutthischapterThischapterdescribestwotoolsprovidedwiththePBNISDK:
Thepbsig125toolgetstheinternalsignatureofaPowerBuilderfunctionfromaPBLname.Thepbx2pbd125toolgeneratesaPBDfromaPBX.
WhenyouinstallPowerBuilder,thesetoolsareinstalledintheSDKsubdirectoryofyourPowerBuilder12.5directoryandinShared\PowerBuilder.
ContentsTopic
pbsig125
pbx2pbd125
pbsig125
DescriptionThePowerBuilderfunctionsignatureistheinternalsignatureofaPowerBuilderfunctionthatisusedtoidentifypolymorphismfunctionsinaclass.Thepbsig125toolobtainsthesefunctionsignaturesfromaPBL.Inheritedfunctions
YoucanalsoobtainasignaturebyselectingthefunctionintheSystemTreeorBrowserandselectingPropertiesfromitspop-upmenu.Thepbsig125tooldoesnotreportthesignatureoffunctionsthatareinheritedfromanancestorobjectunlesstheyareextendedinthedescendant.Forsuchfunctions,youmustusethePropertiesdialogboxtoobtainthesignature.ThePropertiesdialogboxintheBrowseralsoallowsyoutoobtainthesignatureofPowerBuildersystemfunctions.
Syntaxpbsig125pbl_name
ExamplesThiscommandextractsfunctionsignaturesfromoneofthePBLsintheCodeExamplessampleapplication:pbsig125pbexamw1.pbl
Hereissomeoftheoutputfromthepreviouscommand:PBObjectName:w_date_sort
publicsubroutineof_sort(stringas_Column,
stringas_Order)
/*QSS*/
PBObjectName:w_date_window
publicfunctionbooleanof_is_leap_year
(integerai_year)
/*BI*/
publicsubroutineof_days()
/*Q*/
PBObjectName:w_dde_server
publicsubroutinecheck_hotlink(checkboxstatus,
stringdata,stringitem)
/*QCcheckbox.SS*/
PBObjectName:w_dir_treepublicfunctionintegerwf_collapse_rows(datawindow
adw_datawindow,longal_startrow)
/*ICdatawindow.L*/
publicfunctionlongof_recurse_dir_list(string
as_path,longal_parent)
/*LSL*/
publicfunctionstringof_build_dw_tree
(longal_handle)
/*SL*/
ThefollowingexampleillustratestheuseofalettercodetorepresentaPowerBuildersystemclassoracustomclass.Considerthisfunction:functionintegerof_get_all_sales_orders(Refs_sales_orderastr_order[],dateadt_date,integerai_direction)
Forthisfunction,thepbsig125toolreturnsthefollowingstring.Thefirstargumentisanunboundedarrayoftypes_sales_orderandispassedbyreference:/*IRCs_sales_order.[]YI*/
UsageThepbsig125toolgeneratesastringthatrepresentsthedeclarationandsignatureofallthefunctionsandeventsinthePBL,includingargumenttypes,returntypes,andpassingstyle.Eachfunctionandeventisfollowedbyacommentedstring.Youpassthecommentedstring,forexample,QSSinthefirstcommentinthepreviousexample,asthelastargumenttotheGetMethodIDmethod.Forexample,thefollowingoutputindicatesthatthefunctionreturnsanintegerandhasasingleintegerargumentpassedbyreference:/*IRI*/
PowerBuilderarraysPowerBuilderarraysareindicatedwithapairofsquarebrackets[]asasuffix.Forboundedarrays,thebracketsenclosethebounds./*IRCdatastore.RS[]SS*/
PowerBuildersystemorcustomclassAdditionallettercodesrepresentaPowerBuildersystemclassoracustomclass.TheletterCfollowedbythenameofaPowerBuilderobjectorenumeratedclassandaperiod(Cname.)representsanargumentor
returnvalueofthattype.Thefollowingtableshowshowtheoutputfrompbsig125mapstodatatypesandotherentities.
Table8-1:Returnvalueandargumentrepresentationin
pbsig125output
OutputDatatype
[] array
A any
B boolean
C class
D double
E byte
F real
G basictype
H character
I integer
J cursor
K longlong
L long
M decimal
N unsignedinteger(uint)
O blob
P dbproc
Q Notype(subroutine)
S string
T time
U unsignedlong(ulong)
W datetime
Y date
Z objhandle
Thepassingstyleisindicatedbyaprefixonthetype.
Table8-2:Passingstyleandvarargsrepresentationin
pbsig125output
PrefixMeaning
None Passbyvalue
R Passbyreference
X Passasreadonly
V Variablearguments(varargs)
pbx2pbd125
DescriptionThepbx2pbd125toolgeneratesaPowerBuilderdynamiclibrary(PBD)filefromaPowerBuilderextensionPBX.ThegeneratedPBDcanbeaddedtothelibrarylistofanyPowerBuilderapplicationtargetthatwillusetheobjectsandmethodsinthePowerBuilderextension.
Syntaxpbx2pbd125[+]des.pbdsrc1.pbx[src2.pbxsrc3.pbx...srcn.pbx]
ExamplesThisexamplegeneratesanewPBDtest.pbdfromtest.pbx.Theinputandoutputfilesareinthecurrentdirectory:pbx2pbd125test.pbdtest.pbx
ThisexampleappendsgeneratedinformationfromC:\myproject\src.pbxtoC:\mypbds\des.pbd.(Ifdes.pbddoesnotexist,itiscreated.)pbx2pbd125+C:\mypbds\des.pbdC:\myproject\src.pbx
ThisexamplegeneratesanewPBDD:\pbds\test.pbdfromallthePBXfilesintheC:\myprojectdirectory:pbx2pbd125D:\pbds\test.pbdC:\myproject\*.pbx
ThisexamplegeneratesPBDinformationfromallthePBXfilesintheC:\tempandD:\tempdirectoriesandappendstheinformationtotheexistinggeneratedPBDfileD:\pbds\test.pbd:pbx2pbd125+D:\pbds\test.pbdc:\temp\*.pbxd:\temp\*.pbx
UsageYoucanimportanextensionintoaPowerBuilderlibraryusingtheImportPBExtensionpop-upmenuitemforthelibraryinthePowerBuilderSystemTree.PriortoPowerBuilder11.5,youhadtousethepbx2pbdnnntooltocreateaPBDfilefromaPBXfile,thenaddthePBDtothelibrarylistofyourPowerScripttarget.Thetoolisstillavailableinthisrelease.YoucanincludemultiplePBXsinasinglePBDfile.Ifyouwanttoadd
additionalPBXstoanexistingPBD,usetheplus(+)signbeforethenameofthePBD.Thepbx2pbd125toolisinstalledinthesystemPATHintheShared\PowerBuilderdirectorysoyoucaninvokeitinthedirectorywherethePBXsreside.IfyouspecifyanabsolutepathforthePBXfilewhenyougeneratethePBD,thePowerBuilderapplicationsearchesforthePBXonlyinthespecifiedpath.IfyoudonotspecifythepathforthePBXfile,thePowerBuilderapplicationsearchesthesystempathforthePBX.
AppendixThisappendixdescribeswizardsprovidedforMicrosoftVisualStudio.
AppendixA:UsingtheVisualStudioWizards
AboutthisappendixIfyouuseVisualStudio.NET2002or2003orVisualStudio2005,youcanuseawizardtocreateaPBNIextensionproject.Thewizardcreatesaprojectwith.cppand.hfilesthatcontainrequiredcodeaswellastemplatecodetohelpyougetstarted.CheckforwizardupdatesinthePBNIsectionofthePowerBuilderCodeXchangeWebsite.
ContentsTopic
Wherethewizardsareinstalled
GeneratingaPBNIproject
Settingprojectoptions
BuildingandusingthePBX
WherethewizardsareinstalledWhenyouinstallPowerBuilder,thesetupprograminstallsfourdirectoriesintothePowerBuilder12.5\SDK\PBNI\wizardsdirectory:
VCProjects7.0
VCProjects7.1
VCProjects8.0
VCWizards
IfMicrosoftVisualStudioisalreadyinstalledonyourcomputer,thesetupprogramalsoinstallstheappropriatefilesintoyourVisualStudioinstallation.
TableA-1:Wherewizardfilesareinstalled
VisualStudioversion Filescopied Destination
VisualStudio2005
VCProjects
8.0VCWizards
..\MicrosoftVisualStudio8\VC\VCProjects..\MicrosoftVisualStudio8\VC\VCWizards
VisualStudio.NET2003
VCProjects7.1
VCWizards
..\MicrosoftVisualStudio.NET2003\Vc7\VCProjects..\MicrosoftVisualStudio.NET2003\Vc7\VCWizards
VisualStudio.NET2002
VCProjects7.0
VCWizards
..\MicrosoftVisualStudio
.NET\Vc7\VCProjects
..\MicrosoftVisualStudio.NETVc7\VCWizards
IfVisualStudioisnotalreadyinstalledwhenyouinstallPowerBuilder,seetheinstall.txtfileinthePBNI\wizards\VCWizards\PBNIWizarddirectoryforhowtoinstallthewizardlater.TocheckwhetherthewizardisinstalledinVisualStudio,selectFile>New>Projectfromthemenubar,selectVisualC++Projects,and
scrolltheTemplatespanetoseethePBNIwizard.
GeneratingaPBNIprojectThePBNIApplicationWizardletsyouchoosewhethertocreateavisualornonvisualextension,whethertoincludesupportforUnicodeandglobalfunctions,andwhethertogenerateaheaderfile.TocreateanewPBNIproject:
1. StartVisualStudio,selectFile>New>Project,selectVisualC++Projects,andscrolltheTemplatespanetoseethePBNIwizard.
2. SelectPBNIExtensionDLL,enteranameandlocationfortheproject,andclickOK.
3. ClickApplicationSettingsifyouwanttocreateavisualextensionorchangeanyothersettings.ThedefaultistocreateanonvisualextensionwithUnicodesupport.
4. ClickFinish.SeetheReadMe.txtfilecreatedbythewizardforadescriptionofthegeneratedsourceandheaderfiles.
SettingprojectoptionsIftheprojectdoesnotbuildcorrectly,youmightneedtoturnoffprecompiledheadersintheproject'sPropertyPagesdialogboxandsetthepathforthePBNIincludefiles.TosetprojectoptionsforPBNIlibraryandincludefiles:
1. InVisualStudio,selectTools>Options.2. SelectProjectsandSolutions>VC++Directories.3. SelectIncludeFilesfromtheShowDirectoriesFordrop-downlistand
clicktheNewicon.Thenclickthebrowsebutton,browsetothelocationofthePowerBuilder12.5\SDK\PBNI\includedirectory,andclickOK.
4. ClickOKtoclosetheOptionsdialogbox.Bydefault,theprojectiscompiledforUnicodecharactersets.Youcanchangethissettinginthewizard.IfyouwanttochangeittocompileforASCII(SBCS)charactersetsafteryouhavecreatedtheproject,youcanremovethe_UNICODEpreprocessoroption.TocompileforASCIIcharactersets:
1. SelectProject>ProjectNameProperties.2. ExpandC/C++andselectPreprocessor.3. EditthePreprocessorDefinitionstoremove_UNICODEand
UNICODE.
BuildingandusingthePBXWhenyouhavefinishedcodingtheproject,buildtheprojectfromtheBuildmenutocreateaDLLwiththeextension.pbx.Bydefault,theextensioniscreatedintheDebugdirectory.Then,youcanimportthePBXintoaPBLinyourPowerBuildertargetanduseitasdescribedin"Usingtheextension".
IPB_Sessioninterface
DescriptionTheIPB_SessioninterfaceisusedtointeroperatewithPowerBuilder.Anabstractinterface,itdefinesmethodsforaccessingPowerScriptdata,callingPowerScriptfunctions,catchingandthrowingPowerScriptexceptions,andsettingamarshalertoconvertPowerBuilderdataformatstotheuser'scommunicationprotocol.
MethodsThistablelistsfunctionsbycategory.Fulldescriptionsinalphabeticorderfollowthetable.
Table7-2:IPB_Sessionmethodsbycategory
Purpose Method Description
Managingsessions Release
ReleasesthisIPBsession.TheIPB_Sessionobjectbecomesinvalidafterthecall.
Managingobjectreferences AddGlobalRef
AddsaglobalreferencetothespecifiedPowerBuilderobject.
AddLocalRefAddsalocalreferencetothespecifiedPowerBuilderobject.
NewObject Createsanewobjectofthespecifiedtype.
PopLocalFrame
Popsthecurrentlocalreferenceframefromthecurrentnativemethodstackframe.
PushLocalFrame
Pushesalocalreferenceframeontothecurrentnativemethodstackframe.
RemoveGlobalRef
RemovesaglobalreferencetothespecifiedPowerBuilderobject.
RemoveLocalRef
RemovesalocalreferencetothespecifiedPowerBuilderobject.
Managingsharedproperties GetProp
RetrievesapointertothedatavalueofavariablethathasbeenregisteredasasharedpropertyforthecurrentIPBsession.
RemoveProp
RemovesthespecifiedvariablefromthelistofpropertiesofthecurrentIPBsession.
SetProp
Addsanewvariabletothelistofpropertiesofthecurrentsessionorchangesthevalueofanexistingvariable.
HandlingthePowerBuildermessagequeue
ProcessPBMessage
ChecksthePowerBuildermessagequeueand,ifthereisamessageinthequeue,attemptstoprocessit.
Handling Clearsthecurrent
exceptions ClearException PowerBuilderexceptionobject.
GetException Obtainsthecurrentthrownexceptionobject.
HasExceptionThrown
Checksfortheexistenceofanexceptionthathasbeenthrownbutnotcleared.
ThrowException
ThrowsaPowerBuilderexceptionorinheritedexception,replacingtheexistingexceptionifoneexists.
Passingarguments Add<type>Argument
AddsanargumentinavariableargumentPowerBuildercall.
FreeCallInfo FreesmemoryallocatedbyInitCallInfo.
InitCallInfo InitializesthePBCallInfostructure.
FindingPowerBuilderclassesandobjects
FindGroup
Searchesforagroupwithagivennameandgrouptypeinthecurrentlibrarylist.
FindClassSearchesforaclasswithagivennamewithinagivengroup.
FindClassByClassIDSearchesforaclasswithagivennameandagivenID.
GetClassReturnstheclasshandleofaPowerBuilderobject.
GetClassName Returnsthenameofaclassinlowercase.
GetCurrGroup Returnsthenameofthecurrentgroup.
GetSuperClass Returnsthebaseclassofaclass,ifany.
GetSystemClassReturnsthesystemclasshandleofaPowerBuilderobject.
GetSystemGroupReturnstheclassthatcontainsallthesystemglobalfunctions.
IsAutoInstantiate
Returnstrueifthespecifiedclassisanautoinstantiatedclass;otherwisereturnsfalse.
Workingwithfunctionsandevents
FindMatchingFunctionFindsafunctionthathasthespecifiedargumentlist.
GetMethodID ReturnstheIDoftherequestedfunction.
GetMethodIDByEventID
ReturnstheIDofthefunctionthathasagivenpredefinedPowerBuildereventID.
InvokeClassFunction Invokessystemoruserglobalfunctions.
InvokeObjectFunction Invokesaclassmemberfunction.
TriggerEvent TriggersaPowerBuilderevent.
Workingwithenumeratedvariables
GetEnumItemName Obtainsthenameofanenumeratedvariable.
GetEnumItemValue Obtainsthevalueofanenumeratedvariable.
Workingwithglobalvariables GetGlobalVarID Returnsthenameofa
globalvariable.
GetGlobalVarType Returnsthedatatypeofaglobalvariable.
Get<type>GlobalVarReturnsthevalueofaglobalvariableofaspecificdatatype.
GetPBAnyGlobalVarObtainsthevalueofaglobalvariableoftypeAny.
IsGlobalVarArray
Returnstrueiftheglobalvariablecontainsanarray,otherwisereturnsfalse.
IsGlobalVarNull
Returnstrueiftheglobalvariablecontainsanullvalue,otherwisereturnsfalse.
IsGlobalVarObject
Returnstrueiftheglobalvariablecontainsapbobject,otherwise
returnsfalse.
Set<type>GlobalVarSetsthevalueofaglobalvariableofaspecificdatatype.
SetGlobalVarToNull Setsthevalueofasharedvariabletonull.
Workingwithsharedvariables GetSharedVarID Returnsthenameofa
sharedvariable.
GetSharedVarType Returnsthedatatypeofasharedvariable.
Get<type>SharedVarReturnsthevalueofasharedvariableofaspecificdatatype.
GetPBAnySharedVarObtainsthevalueofasharedvariableoftypeAny.
IsSharedVarArray
Returnstrueifthesharedvariablecontainsanarray,otherwisereturnsfalse.
IsSharedVarNull
Returnstrueifthesharedvariablecontainsanullvalue,otherwisereturnsfalse.
IsSharedVarObject
Returnstrueifthesharedvariablecontainsapbobject,otherwisereturnsfalse.
Set<type>SharedVarSetsthevalueofasharedvariableofa
specificdatatype.
SetSharedVarToNullSetsthevalueofasharedvariabletonull.
Workingwitharrays Get<type>ArrayItem
Returnsthevalueofanarrayitemofaspecificdatatype.
GetArrayInfo Obtainsinformationaboutanarray.
GetArrayItemType Obtainsthedatatypeofaniteminanarray.
GetArrayLength Returnsthelengthofanarray.
GetPBAnyArrayItem ObtainsthevalueofanarrayitemoftypeAny.
IsArrayItemNullReturnstrueifthearrayitemcontainsanarray,otherwisereturnsfalse.
NewBoundedSimpleArray Createsaboundedsimpledataarray.
NewUnboundedSimpleArray Createsanunboundedsimpledataarray.
NewBoundedObjectArrayCreatesaboundedPowerBuilderobjectorstructurearray.
NewUnboundedObjectArrayCreatesanunboundedPowerBuilderobjectorstructuredataarray.
Releasesmemory
ReleaseArrayInfo returnedbyGetArrayInfo.
Set<type>ArrayItemSetsthevalueofanarrayitemofaspecificdatatype.
SetArrayItemToNull Setsthevalueofanarrayitemtonull.
Workingwithstrings GetStringLength
Returnsthelengthofastringinbyteswithouttheterminator.
GetStringReturnsapointertothestringpassedinasanargument.
NewString Createsanewstring.
ReleaseString Releasesthememoryusedbyastring.
SetStringFreesanexistingstringandassignsanewstringvaluetoit.
Workingwithbinarylargeobjects
GetBlob Returnsapointertothedatabufferforablob.
GetBlobLengthReturnsthelengthinbytesofblobdatainabuffer.
NewBlobCreatesanewblobandduplicatesabufferforthenewblobdata.
Destroystheexisting
SetBlob datainablobandcopiesdataintoitfromabuffer.
Workingwithdecimalvalues GetDecimalString
Convertsdecimaldatainapbdecobjecttoastring.
NewDecimal Allocatesresourcesforanewdecimaldataobject.
ReleaseDecimalStringFreesthememoryacquiredusingGetDecimalString.
SetDecimal Convertsastringtoadecimal.
Workingwithdateandtimevalues GetDateString Convertsdataina
pbdateobjecttoastring.
GetDateTimeStringConvertsdatainapbdatetimeobjecttoastring.
GetTimeString Convertsdatainapbtimeobjecttoastring.
NewDate Createsanewpbdatedataobject.
NewDateTime Createsanewpbdatetimedataobject.
NewTime Createsanewpbtimedataobject.
ReleaseDateStringFreesthememoryacquiredusingGetDateString.
ReleaseDateTimeStringFreesthememoryacquiredusingGetDateTimeString.
ReleaseTimeStringFreesthememoryacquiredusingGetTimeString.
SetDate Resetsthevalueofthespecifiedpbdateobject.
SetDateTimeResetsthevalueofthespecifiedpbdatetimeobject.
SetTime Resetsthevalueofthespecifiedpbtimeobject.
SplitDateSplitsthespecifiedpbdateobjectintoayear,month,andday.
SplitDateTimeSplitsthespecifiedpbdatetimeobjectintoayear,month,andday.
SplitTimeSplitsthespecifiedpbtimeobjectintoayear,month,andday.
Workingwithdatavalues AcquireArrayItemValue
ClonesthedatainthePBCallInfostructureinanarrayitemandresetstheIPB_Valuepointer.
AcquireValue
ClonesthedatainthePBCallInfostructureandresetstheIPB_Valuepointer.
ReleaseValueFreesthevalueacquiredbytheAcquireValueorAcquireArrayItemValuemethod.
SetValue
SetsthevalueofoneIPB_ValueobjecttothevalueofanotherIPB_Valueobject
Workingwithfields GetFieldID
ObtainstheinternalIDofaclassinstancevariable.
GetFieldName Obtainsthenameofthespecifiedfield.
GetFieldTypeObtainsthedatatypeofaclassinstancevariable.
GetNumOfFieldsObtainsthenumberoffieldsinthespecifiedclass.
GetPBAnyField ObtainsthevalueofavariableoftypeAny.
Get<type>FieldObtainsapointertotheinstancevariabledataforaspecifiedvariable.
IsFieldArrayReturnstrueifthefieldcontainsanarray,otherwisereturnsfalse.
IsFieldNull
Returnstrueifthefieldcontainsanullvaluearray,otherwisereturnsfalse.
IsFieldObjectReturnstrueifthefieldcontainsapbobject,otherwisereturnsfalse.
Set<type>Field
Asetofdatatype-specificfunctions.Setsthevalueofaninstancefieldofanobject.
Set<type>Field
Asetofdatatype-specificfunctions.Setsthevalueofaninstancefieldofanobject.
UpdateFieldRefreshesavisualpropertyofaPowerBuilderobject.
Workingwithnativeclasses GetNativeInterface
Obtainsapointertotheinterfaceofanativeclass.
IsNativeObjectDetermineswhetherapbobjectisaninstanceofanativeclass.
AccessingresultsetsfromDataWindowsandDataStores
CreateResultSet
CreatesaresultsetobjectusingapointertoanIPB_ResultSetAccessorobject.
GetResultSetAccessor
Obtainsaninterfacethroughwhichyoucanreaddatafromaresultset.
ReleaseResultSetAccessorReleasesthepointerobtainedusing
GetResultSetAccessor.
Workingwithmarshalerextensions
GetMarshalerObtainsthemarshalerobjectassociatedwithaproxyobject.
NewProxyObjectCreatesaproxyforaremoteobject.
SetMarshaler
SetsamarshalerthatwillbeusedtoinvokeremotemethodsandconvertPowerBuilderdataformatstotheuser'scommunicationprotocol.
IPB_Argumentsinterface
DescriptionTheIPB_ArgumentsandIPB_ValueinterfacesareusedtopassvaluesbetweenthePowerBuilderVMandPowerBuilderextensionmodules.EachargumentisrepresentedbyapointertotheIPB_Valueinterface.
MethodsTheIPB_Argumentsinterfacehastwomethods,GetAtandGetCount.
IPB_ResultSetAccessorinterface
DescriptionTheIPB_ResultSetAccessorinterfaceisusedtoaccessresultsetsinDataWindowandDataStoreobjects.
MethodsTheIPB_ResultSetAccessorinterfacehassixmethods:
AddRefGetColumnCountGetColumnMetaDataGetItemDataGetRowCountRelease
IPB_RSItemDatainterface
DescriptionTheIPB_RSItemDatainterfaceisusedasanargumenttotheGetItemDatafunctionofIPB_ResultSetAccessor.
MethodsTheIPB_RSItemDatainterfacehastwomethods:SetDataandSetNull.
IPB_Valueinterface
DescriptionTheIPB_ArgumentsandIPB_ValueinterfacespassvaluesbetweenthePowerBuilderVMandPowerBuilderextensionmodules.ThroughtheIPB_Valueinterface,youcanaccessinformationabouteachvariable,includingitstype,nullflag,accessprivileges,arrayorsimpletype,andreferencetype.
MethodsTable7-4:IPB_Valuemethods
Method Description
Get<type>Setofdatatype-specificmethodsthatreturnapointertothedatainIPB_Value
GetClass ReturnstheclasshandleofaPowerBuilderobject
GetType Returnsthedatatypeofasingledataitemorarray
IsArray ReturnstrueiftheIPB_Valueinstancecontainsanarray,otherwisereturnsfalse
IsByRef ReturnstrueiftheIPB_Valueinstanceispassedbyreference
IsEnum ReturnstrueiftheIPB_Valueinstancecontainsanullvalue,otherwisereturnsfalse
IsObject ReturnstrueiftheIPB_Valueinstancecontainsanobjectorobjectarray,otherwisereturnsfalse
SetToNull UsedtosetthedatacontainedintheIPB_Valueinstancetonullsothatdatacanbereset
Set<type> Setofdatatype-specificmethodsthatsetthevalueoftheIPB_Valueinstance
IPB_VMinterface
DescriptionTheIPB_VMinterfaceloadsPowerBuilderapplicationsinthird-partyapplicationsandinteroperateswiththePowerBuildervirtualmachine(PBVM).
MethodsIPB_VMhastwomethods:
CreateSessionRunApplication
IPBX_Marshalerinterface
DescriptionTheIPBX_MarshalerinterfaceisusedtoinvokeremotemethodsandconvertPowerBuilderdataformatstotheuser'scommunicationprotocol.AmarshalerextensionisaPowerBuilderextensionthatactsasthebridgebetweenPowerBuilderandothercomponents,suchasEJBs,Javaclasses,CORBAobjects,Webservices,andsoon.
MethodsTable7-5:IPBX_Marshalermethods
Method Description
Destroy DestroysaninstanceofanobjectinheritedfromtheIPBX_Marshalerstructure
GetModuleHandle ReturnsthehandleofthePBXthatcontainsthenativeclass
InvokeRemoteMethodUsedinPowerBuildermarshalernativeclassestocallremotemethods
IPBX_NonVisualObjectinterface
DescriptionTheIPBX_NonVisualObjectinterfaceinheritsfromIPBX_UserObjectandisthedirectancestorclassofnonvisualPowerBuildernativeclasses.
MethodsIPBX_NonVisualObjectinheritstwomethodsfromtheIPBX_UserObjectinterface:DestroyandInvoke.
IPBX_UserObjectinterface
DescriptionTheIPBX_UserObjectinterfaceistheancestorclassofthePowerBuildernativeclasses.
MethodsIPBX_UserObjecthastwomethods:DestroyandInvoke
IPBX_VisualObjectinterface
DescriptionTheIPBX_VisualObjectinterfaceinheritsfromIPBX_UserObjectandisthedirectancestorclassofvisualPowerBuildernativeclasses.
MethodsIPBX_VisualObjecthasthreedirectmethods:
CreateControlGetEventIDGetWindowClassName.
IPBX_NonVisualObjectinheritstwomethodsfromtheIPBX_UserObjectinterface:
DestroyInvoke
PBArrayInfostructure
DescriptionPBArrayInfoisaC++structureusedtoholdinformationaboutarrays.
Table7-6:PBArrayInfomembers
Member Type Description
ArrayBound Localstructdeclaration
Structureoftypepblongcontainingtheboundaries(upperBound,lowerBound)ofadimension.
BoundedArray Enumdata UsedinarrayTypetoidentifythatthearrayisaboundedarray.
UnboundedArray Enumdata UsedinarrayTypetoidentifythatthearrayisanunboundedarray.
arrayType EnumtypeUsedinIPB_Session::GetArrayInfotoidentifythedatatypeofthearray.Donotsetthisvariablemanually.
valueType pbuint
Thedatatypeofarrayitems.Setittopbvalue_typeifitisasimpletype,orpbobjectiftheitemisaclassorstructure.
numDimensions pbuintNumberofdimensionsofthearray.Anunboundedarraycanhaveonlyonedimension.Thelowerboundisone.
bounds ArrayBound[] Arrayboundsdeclarationarray,usedinaboundedarray.
PBCallInfostructure
DescriptionPBCallInfoisaC++structureusedtoholdargumentsandreturntypeinformationinfunctioncallsbetweenPBNIandPowerBuilder.
Table7-7:PBCallInfomembers
Member Type Description
pArgs IPB_Arguments* Interfaceusedtoaccessarguments
returnValue IPB_Value Holdsreturndataafterthecall
returnClass pbclass Holdsreturnclassafterthecall
PB_DateDatastructure
DescriptionThePB_DateDatastructureisusedtopassdataoftypeDateintheSetDatafunctionintheIPB_RSItemDatainterface.
Table7-8:PB_DateDatamembers
Field Description
year Ashortidentifyingtheyear
monthAshortidentifyingthemonth
day Ashortidentifyingtheday
filler Ashortusedforstructurealignmentonly
SeeAlsoSetData
PB_DateTimeDatastructure
DescriptionThePB_DateTimeDatastructureisusedtopassdataoftypeDateTimeintheSetDatafunctionintheIPB_RSItemDatainterface.
Table7-9:PB_DateTimeDatamembers
FieldDescription
date APB_DateDatastructureidentifyingthedate
time APB_TimeDatastructureidentifyingthetime
SeeAlsoSetData
PB_TimeDatastructure
DescriptionThePB_TimeDatastructureisusedtopassdataoftypeTimeintheSetDatafunctionintheIPB_RSItemDatainterface.
Table7-10:PB_DateDatamembers
Field Description
hour Ashortidentifyingthehour
minute Ashortidentifyingtheminute
secondAshortidentifyingthesecond
filler Ashortusedforstructurealignmentonly
SeeAlsoSetData
PBX_DrawItemStructstructure
DescriptionThePBX_DrawItemStructstructurecontainsthepropertiesofanexternalvisualcontrolthatyouwanttodrawusingthePBX_DrawVisualObjectfunction.
Table7-11:PBX_DrawItemStructmembers
Field Description
x Xcoordinateofthevisualcontrolrelativetoitsparentcontrol(forexample,thewindowthatcontainsit).
y Ycoordinateofthevisualcontrolrelativetoitsparentcontrol.
width Widthofthevisualcontrol.
height Heightofthevisualcontrol.
objectNameThenameofthevisualobject,forexample:uo_1.
tag Fieldtobeusedtopassanyvalueattheuser'sdiscretion.
enabled Whetherthevisualcontrolisenabled.Possiblevaluesaretrueandfalse.
visible
Whetherthevisualcontrolisvisible.Possiblevaluesaretrueandfalse.Inthedevelopmentenvironment,PowerBuilderdoesnotcallthePBX_DrawVisualObjectfunctionifthisfieldissettofalseandtheDesign>ShowInvisiblesmenuitemisnotselected.
borderstyle
Borderstyleofthevisualcontrol.Avalueofthepbborder_styleenumeratedvariable.Possiblevaluesare:
0–none1–shadowbox
2–box5–lowered6–raised
backColorBackgroundcolorofthevisualcontrol.YoucanobtaintheRGBvalueofthebackgroundcolorusingtheWindowsAPIfunctionsGetRValue,GetGValue,andGetBValue.
SeeAlsoPBX_DrawVisualObject
PBArrayAccessortemplateclass
DescriptionTherearetwoversionsofthePBArrayAccessortemplateclass.Thefirstversionisusedtoaccesstheitemsinanarrayofastandardtype.Thesecondversionisusedtoaccessitemsinastringarray.ThestandardtypesaredefinedasValueTypesinpbtraits.handarepbint,pbuint,pbbyte,pblong,pblonglong,pbulong,pbboolean,pbreal,pbdouble,pbdec,pbdate,pbtime,pbdatetime,pbchar,pbblob,andpbstring.PBArrayAccessorhasfourmethods:
GetAtIsNullSetAtSetToNull
PBBoundedArrayCreatortemplateclass
DescriptionTherearetwoversionsofthePBBoundedArrayCreatortemplateclass.Thefirstversionisusedtocreateaboundedarrayofastandardtype.ThestandardtypesaredefinedasValueTypesinpbtraits.handarepbint,pbuint,pbbyte,pblong,pblonglong,pbulong,pbboolean,pbreal,pbdouble,pbdec,pbdate,pbtime,pbdatetime,pbchar,pbblob,andpbstring.Thesecondversionisusedtocreateaboundedarrayofstrings.
MethodsPBBoundedArrayCreatorhastwomethods:
GetArraySetAt
PBBoundedObjectArrayCreatorclass
DescriptionThePBBoundedObjectArrayCreatorclassisusedtocreateanobjectarray.
MethodsPBBoundedObjectArrayCreatorhastwomethods:
GetArraySetAt
PBObjectArrayAccessorclass
DescriptionThePBObjectArrayAccessorclassisusedtoaccesstheitemsinanobjectarray.
MethodsPBObjectArrayAccessorhastwomethods:
GetAtSetAt
PBUnboundedArrayCreatortemplateclass
DescriptionTherearetwoversionsofthePBUnboundedArrayCreatortemplateclass.Thefirstversionisusedtocreateanunboundedarrayofastandardtype.ThestandardtypesaredefinedasValueTypesinpbtraits.handarepbint,pbbyte,pbuint,pblong,pblonglong,pbulong,pbboolean,pbreal,pbdouble,pbdec,pbdate,pbtime,pbdatetime,pbchar,pbblob,andpbstring.Thesecondversionisusedtocreateanunboundedarrayofstrings.
MethodsPBUnboundedObjectArrayCreatorhastwomethods:
GetArraySetAt
PBUnboundedObjectArrayCreatorclass
DescriptionThePBUnboundedObjectArrayCreatorclassisusedtocreateanobjectarray.
MethodsPBUnboundedObjectArrayCreatorhastwomethods:
GetArraySetAt
Exportedmethods
DescriptionThefollowingtablelistsmethodsthatmustbeimplementedinthePowerBuilderextensionmodulewhentheconditionsshowninthetableapply.Themethodsaredescribedafterthetable.ThePBX_GetVersionmethodisusedbyPowerBuildertodeterminewhetherthecompilermacroUNICODEor_UNICODEhasbeenset.Itisforinternaluseonly.
MethodsTable7-12:Methodsthatmustbeexportedbyallextensions
Method Required
PBX_CreateNonVisualObjectWhentheextensioncontainsnonvisualnativeclasses
PBX_CreateVisualObject Whentheextensioncontainsvisualnativeclasses
PBX_DrawVisualObjectWhenyouwanttobeabletodrawavisualrepresentationofthevisualobjectinthePowerBuilderdevelopmentenvironment
PBX_GetDescription Inallextensions
PBX_InvokeGlobalFunction Whentheextensioncontainsglobalfunctions
PBX_Notify Whenyouneedtoinitializeanduninitializeasession
MethodexportedbyPowerBuilderVM
DescriptionThismethodisexportedbythePowerBuilderVM:
PB_GetVM