PowerBuilder Native Interface Programmers Guide and Reference · PowerBuilder application uses an...
Transcript of PowerBuilder Native Interface Programmers Guide and Reference · PowerBuilder application uses an...
PowerBuilderNativeInterfaceProgrammersGuideandReference
Audience
ThisbookisforC++programmerswhowillusethePowerBuilder®NativeInterface(PBNI)tobuildPowerBuilderextensions.ThebookassumesthatyouarefamilarwiththeC++languageandaC++developmenttool.
Relateddocuments
ThisbookcontainsinformationaboutbuildingPowerBuilderextensions.ThePowerBuilderExtensionReferencecontainsinformationaboutusingextensionsthatareprovidedwithPowerBuilder.
DocumentationWebsite
TheAppeonProductDocumentationWebsiteisaccessibleusingastandardWebbrowser.ToaccesstheAppeonProductManualswebsite,gotoProductManuals.
Conventions
Theformattingconventionsusedinthismanualare:
Formattingexample Toindicate
RetrieveandUpdate
Whenusedindescriptivetext,thisfontindicates:Command,function,andmethodnamesKeywordssuchastrue,false,andnullDatatypessuchasintegerandcharDatabasecolumnnamessuchasemp_idandf_nameUser-definedobjectssuchasdw_emporw_main
Whenusedindescriptivetextandsyntaxdescriptions,obliquefontindicates:
variableorfilename
Variables,suchasmyCounterPartsofinputtextthatmustbesubstituted,suchaspblname.pbdFileandpathnames
File>Save
Menunamesandmenuitemsaredisplayedinplaintext.Thegreaterthansymbol(>)showsyouhowtonavigatemenuselections.Forexample,File>Saveindicates"selectSavefromtheFilemenu."
dw_1.Update()
Monospacefontindicates:InformationthatyouenterinadialogboxoronacommandlineSamplescriptfragmentsSampleoutputfragments
Ifyouneedhelp
EachAppeoninstallationthathaspurchasedasupportcontracthasoneormoredesignatedpeoplewhoareauthorizedtocontactAppeonTechnicalSupport.Ifyoucannotresolveaproblemusingthedocumentationoronlinehelp,pleasehavethedesignatedpersoncontactAppeonTechnicalSupport.
ProgrammersGuideThispartprovidesanintroductiontothePowerBuilderNativeInterfaceandaguidetocreatingPowerBuilderextensionsandinteractingwithPowerBuilder.
IntroductiontoPBNI
Aboutthischapter
ThischapterprovidesabriefintroductiontothePowerBuilderNativeInterface.
Contents
Topic
AboutPBNI
TheelementsofPBNI
ThePBNISDK
ComparingPBNIandJNI
AboutPBNIPBNIisastandardprogramminginterfacethatenablesdeveloperstoextendthefunctionalityofPowerBuilder.UsingPBNI,youcancreateextensionstoPowerBuilder—nonvisual,visual,andmarshalerextensions—andembedthePowerBuildervirtualmachine(PBVM)intoC++applications.ThroughtheJavaNativeInterface(JNI)andPBNI,JavaapplicationscanalsocommunicatewiththePBVM.Usewith.NETtargets
Youcanusethebuilt-inWebservicesclientextension(pbwsclient170.pbx)inapplicationsthatyouplantodeployto.NETasaPowerBuilder.NETWindowsFormsapplication.YoucannotuseanyotherPBNIextensionsina.NETtarget.Codesamples
ThisdocumentationcontainstwocompletebutverysimpleexamplesthatillustratesomebasicprinciplesofusingthePowerBuilderNativeInterface(PBNI):"Nonvisualextensionexample"and"CreatingaPowerBuilderobjecttobecalledfromC++".Formorereal-worldexamples,seethePBNIsectionofthePowerBuilderCodeSamplesWebsite.Thefollowingdiagramillustratesthetwo–waycommunication,withbothPowerBuilderextensionsandexternalapplications,thatPBNIprovidesforthePBVM.Asthediagramshows,aPowerBuilderextensioncommunicateswiththePBVMthroughtheIPB_Sessioninterface,andthePBVMcommunicateswiththeextensionthroughaninterfacederivedfromIPBX_UserObject.C++andJavaextensionscommunicatewiththePBVMthroughtheIPB_VMandIPB_Sessioninterfaces.Figure1-1:InteractionbetweenthePBVMandexternalapplicationsandextensions
UnderstandingPowerBuilderextensionsAPowerBuilderextensionisjustwhatitsnamesuggests:anextensiontoPowerBuilderfunctionalityprovidedbyyou,byathirdparty,orbyAppeon.AllPowerBuilderextensionscommunicatewiththePBVMthroughaninterfacecalledIPB_Session.ThisinterfaceandotherPBNIobjectsandinterfacesaredescribedin"TheelementsofPBNI".PowerBuilderprovidesitsownextensions,includingaPBDOMXMLparserandclassesthatsupportSOAPclientsforWebservices.Infuturereleases,AppeonmightdevelopmorenewfeaturesasPBNIextensionsinsteadofembeddingtheminthePowerBuilderVM(PBVM),sothatthesizeofthePBVMcanbeminimized.Extensionsarealsoavailablefromthirdpartycontributors;forthelatestsamplesandutilities,seethePBNIsectionofthePowerBuilderCodeSamplesWebsite.
Nonvisualextensions
ThemostfrequentlyusedtypeofPowerBuilderextensionisanonvisualextension.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.
Visualextensions
VisualextensionscanbeusedasiftheywerePowerBuildervisualuserobjects—youcanplacetheminwindowsoronothervisualcontrols.VisualextensionsallowyoutocreateasubclassoftheWindowsprocedure(winproc)ofavisualcomponentsothatyoucanusethelatest"lookandfeel"foryourapplications.
Marshalerextensions
MarshalerextensionsactasbridgesbetweenPowerBuilderandothercomponents,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.
InteractingwithJava
TocallJavaclassesfromPowerBuilder,youcanbuildamarshalerextensionthatinvokesJavamethodsthroughJNI,asdescribedinChapter3,"CreatingMarshalerExtensions."YoucanalsouseJNItoallowJavatocallintoPowerBuilderthroughCorC++.Foranexample,seethePowerBuilderCodeSamplesWebsite.
TheelementsofPBNIToenablethefeaturesdescribedintheprevioussection,PBNIprovidesinterfaces,structures,globalfunctions,andhelperclasses.Theseelementsaredescribedinmoredetailinthereferencesectionofthisguide.SeeChapter7,"PBNIInterfaces,Structures,andMethods."Thissectionprovidesanoverview.
Interfaces
TheIPB_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.YoumustimplementtheInvokeRemoteMethodmethodintheinheritedclasstoenablePowerBuildertoinvokemethodsonremoteobjectsrepresentedbyaproxy.
Structures
ThePBCallInfostructureholdsargumentsandreturntypeinformationforfunctioncallsbetweenPBNIandPowerBuilder.ToaccesstheinformationinPBCallInfo,usetheIPB_Argumentsinterface.ThePBArrayInfostructurestoresinformationaboutarrays.ThePB_DateData,PB_TimeData,andPB_DateTimeDatastructuresareusedtopassDataWindowandDataStoredata.
Globalfunctions
EveryPowerBuilderextensionobjectmustexportglobalfunctionsthatenablethePowerBuilderVMtocreateinstancesoftheobjectanduseitsmethods.ThePBX_GetDescriptionfunctiondescribestheclassesandfunctionsintheextension.ThePBX_CreateNonVisualObjectfunctionenablesthePBVMtocreateinstancesofthenonvisualclassesinanextension,andthePBX_CreateVisualObjectfunctiondoesthesameforvisualclasses.
Helperclasses
Severalhelperclasses,suchasPBObjectCreator,PBArrayAccessor,andPBEventTrigger,makeiteasiertoprogramwithPBNI.
InteractionbetweenanextensionandthePBVM
ThefollowingdiagramsummarizeshowanextensioninteractswiththePBVM.Figure1-2:InteractionbetweenanextensionandthePowerBuilderVM
ThePBNISDKWhenyouinstallPowerBuilder,theSoftwareDevelopmentKit(SDK)forPBNIisinstalledinthePowerBuilder15.0\SDK\PBNIdirectory.TheSDKtools,pbsig170andpbx2pbd170,arealsoinstalledintheShared\PowerBuilderdirectorysothattheyareavailableinyourpath.TheSDKcontainsthecomponentsshowninthefollowingtable.
Table1-1:ContentsofthePBNISDK
Component Description
pbx2pbd170.exe
AtoolthatgeneratesaPBDfilefromaPowerBuilderextensionfile.TheextensionfileisaDLLfilethatmustexportasetofPBNIfunctions.TheDLLisusuallycalledaPBXandcanbegiventhesuffix.pbx.
pbsig170.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\VCProjectsAMicrosoftVisualStudio.NET2002wizardthat
7.0 makesiteasierforyoutocreatePBNIprojects.
wizards\VCWizards FilesrequiredbytheVisualStudiowizards.
pbni170.hlp,pbni170.cnt
HelpfilesforPBNI.
ComparingPBNIandJNIIfyouhaveusedtheJavaNativeInterface(JNI),whichallowsJavaapplicationsandCandC++modulestointeroperate,youmightfindithelpfultobeawareofthesimilaritiesinthetwointerfacesandthedifferencesbetweenthem.TheIPB_VMinterfaceinPBNIisanalogoustotheJavaVMtype,andtheIPB_SessioninterfaceinPBNIisanalogoustoJNIEnv.ForJNI,youusethejavapcommandtoobtainastringthatencodesthesignatureofeachmethodinanativeclass.ForPBNI,thepbsig170toolperformsthesamefunction.Themajordifferencebetweenthetwointerfacesisinhowanativefunctionorclassisdeclared.InJNI,youmustusethenativekeywordtodeclarethatafunctionisnative,butyoucannotsimplydeclareaclassasnative.YoumustdefineyourclassesinJavasourcecode,usethejavahtooltogenerateaCheaderfilethatdefinesaCprototypeforeachnativemethod,thenimplementtheindividualCorC++functions,using#includetoincludethegeneratedheaderfile.PBNIprovidesanobject-orientedapproach—youdeclareaclassasnativeintheC++codebyinheritingfromtheIPBX_NonVisualObjectorIPBX_VisualObjectstruct.
BuildingPowerBuilderExtensions
Aboutthischapter
ThischapterdescribeshowtobuildaPowerBuilderextension.Itbeginswithasampleapplicationthatusesasimplenonvisualextension.
Contents
Topic
Nonvisualextensionexample
CreatingaPowerBuilderextension
AddinganextensiontoaPowerBuildertarget
Usingtheextension
Creatingandusingavisualextension
Creatingvisualclassinstances
Eventprocessinginvisualextensions
CallingPowerScriptfromanextension
Exceptionhandlinganddebugging
NonvisualextensionexampleToillustratetheprinciplesinvolvedinbuildingandusinganextension,thischapterstartswithasampleapplicationthatusesaPowerBuilderextensiontoperformasimplearithmeticoperation.Ordinarily,thisisnotataskthatneedsPBNI,butitisusedheretomakethebasicprocessclear.Therestofthischapterdescribesbuildingextensionsinmoredetail.PBXfilesuffix
PowerBuilderextensionsareDLLfilesbuttypicallyusethefileextension.pbxinsteadof.dll.YourextensioniscompiledintoaPBXfilebydefaultifyouusethewizarddescribedinAppendixA,"UsingtheVisualStudioWizards"Formorerealisticexamples,seethePowerBuilderCodeSamplesWebsite.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.MakesuretheincludedirectoryinPowerBuilder15.0\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.
Requiredmethods
AllPowerBuildernonvisualextensionsmustexporttwomethods: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,seethePowerBuilderCodeSamplesWebsite.
Step2:DefinetheclassesandfunctionsintheextensionYourC++codemustexposetwostandardmethodsthatenablePowerBuildertorecognizeeachnativeclassandcreateinstancesoftheclass.OneofthesemethodsisPBX_GetDescription.UsePBX_GetDescriptiontopassthedescriptionsofclassesandglobalfunctionsinthePowerBuilderextensiontoPowerBuilder.Everyextensionmustexportthismethod.ImportingthePBXorDLLfileintoaPBLconvertsthedescriptionoftheextensionintoPowerScriptandaddsittothePBLassourcecode.ThekeywordnativeinthesourcecodeindicatesthatthePowerBuildertypewasdefinedinanextension.Alltheclassesorglobalfunctionsinanextensionmodulearepassedinasingledescription.Theexamplesthatfollowillustratehowyoudefineclassesandfunctionsinadescription.Forthefullsyntax,seePBX_GetDescription.
Describingnonvisualclasses
NonvisualclassescaninheritfromtheNonVisualObjectPowerBuildersystemclassoranyofitsdescendants.Whileanativeclasscaninheritfromauser–defineduserobject,Appeonrecommendsthatyouuseonlysystemclasses.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;
}
Describingvisualclasses
VisualnativeclassescaninheritonlyfromtheUserObjectPowerBuildersystemclass.ThePowerBuilderVMconsidersanyclassthatinheritsfromUserObjecttobeavisualclass.Allothernativeclassesareconsideredtobenonvisualclasses.Formoreinformationabouthowtodescribevisualclasses,see"Creatingandusingavisualextension".
Describingglobalfunctions
Anextensioncanincludeglobalfunctionsaswellasclasses.Thisexampleshowsadescriptionfortwoglobalfunctions:"globalfunctions\n"\
"functionintg_1(inta,intb)\n"\
"functionlongg_2(longa,longb)\n"\
"endglobalfunctions\n"
ThesyntaxandusageofglobalfunctionsdefinedinanextensionarethesameasforglobalfunctionsdefinedintheFunctionpainterinPowerBuilder.Globalfunctionscannotbeoverloaded
LikeglobalfunctionsinPowerScript,globalfunctionsinaPowerBuilderextensioncannotbeoverloaded.
Usingforwarddeclarations
PowerBuilderextensionscanprovidemultipleclasses.Aclasscanreferenceanyclassthatisdefinedearlierinthedescription,butifitreferencesaclassdefinedlaterinthedescription,youmustprovideaforwarddeclaration.Thisexampleshowsadescriptionthatincludes
forwarddeclarationsfortwoclasses,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,typicallyPowerBuilder15.0\SDK\PBNI\include,mustbeinyourincludepath.Ifyouuseanyhelperclasses,makesurethesourcefilethatcontainsthemisaddedtoyourproject.Foralistofclasses,seethetablein"ThePBNISDK".
NowyouarereadytousetheextensioninaPowerBuilderapplication.
AddinganextensiontoaPowerBuildertargetThesimplestwaytoaddaPowerBuildernativeclasstoaPowerBuildertargetistoimporttheobjectdescriptionsinthePBXfileintoalibraryinthePowerBuilderSystemTree.Youcanalsouseacommand-linetooltocreateaPBDfilefromaPBXfileandaddittothetarget'slibrarysearchpath.Seepbx2pbd170.Toimportthedescriptionsinanextensionintoalibrary:
1. CopythePBXfileintoadirectoryontheapplication'spath.2. IntheSystemTree,expandthetargetinwhichyouwanttousethe
extension,right-clickalibrary,andselectImportPBExtensionfromthepop-upmenu.
3. NavigatetothelocationofthePBXfileandclickOpen.EachclassinthePBXdisplaysintheSystemTreesothatyoucanexpandit,viewitsproperties,events,andmethods,anddraganddroptoaddthemtoyourscripts.
Usingtheextension
Usingnonvisualclasses
InPowerScript,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)
DestroyingthePBNIobjectinstance
WhenthePowerBuilderapplicationnolongerneedsaninstanceofanonvisualclassandaDESTROYstatementisissued,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,seethePowerBuilderCodeSamplesWebsite.
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.
CodesamplesThecodefragmentsintherestofthissectionarebasedoncompletesampleapplicationsthatyoucanfindonthePowerBuilderCodeSamplesWebsite.
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;
};
Registeringthewindowclass
BeforeCreateControlcanbecalled,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;
}
ImplementingCreateControl
EveryvisualnativeclassmustimplementtheIPBX_VisualObject
CreateControlmethod.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;
}
Capturingmessagesandmouseclicks
ThecodeintheextensioncapturestheWindowsmessagesthatcausethewindowtobedrawn,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);
}
Triggeringclickevents
ThefollowingistheTriggerEventmethodthattriggerstheOnclickandOndoubleclickevents: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;
}
Generatingeventsyntaxautomatically
ImportingtheextensiongeneratestheOnclickandOndoubleclickeventswiththeappropriateargumentsautomatically,andatruntime,thePBVMfirestheevents.YoudonotneedtocapturetheWindowsmessagesWM_LBUTTONUPandWM_LBUTTONDBLCLKintheextension.Inthefollowingdescription,onclickistheeventnameandpbm_lbuttonupistheeventtokenname.Noticethattheeventnameisnotfollowedbyemptyparenthesesasitiswhenyouusethereturntypeandargumentstechniquefordescribingtheevent:"eventonclickpbm_lbuttonup\n"
Aboutthetokenname
ThetokennameisastringthatmapstoaninternalPowerBuildereventIDdefinedintheheaderfilepbevtid.h.ThefirstIDinthisfileisPB_NULL.ForallotherIDsinthefile,thereisafixedrelationshipbetweenthenamethatyouuseinthedescriptionandtheeventIDinpbevtid.h.ThenameisthesameastheIDwiththelettermappendedtothepbprefix.Youmustuselowercaseinthedescription.Forexample,theeventIDPB_ACTIVATEinpbevtid.hmapstothetokennamepbm_activate.Inthedescriptionprovidedwith
PBX_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.
UsingGetMethodID
Togetthefunction'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.Youcanusethepbsig170command-linetooltoobtainafunction'ssignature.However,thepbsig170tooldoesnotreportthesignatureoffunctionsthatareinheritedfromanancestorobjectunlesstheyareextendedinthedescendant,anditdoesnotreporteventsignatures.Formoreinformationaboutusingpbsig170,andanexplanationofalltheformatsusedinthesignature,seepbsig170.
UsingFindMatchingFunction
InsteadofthestringthatGetMethodIDuses,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");
InvokingPowerBuilderfunctions
ThefollowingmethodsarethoseyouusemostfrequentlytoinvokePowerBuilderfunctions.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.
Debugging
YoucannoteditanativeclassinthePowerBuilderdevelopmentenvironment,andyoucannotenternativemethodsinthePowerBuilderdebuggerbecausethemethodsareC++methods.YoumustuseaC/C++debuggertodebuganextensionmodule.
CreatingMarshalerExtensions
Aboutthischapter
Thischapterdescribeshowtocreatemarshalerextensions.
Contents
Topic
Aboutmarshalerextensions
DevelopingthePowerBuilderextension
GeneratingproxiesforJavaclasses
CallingtheJavaclassfromPowerBuilder
AboutmarshalerextensionsMarshalerextensionscanactasbridgesbetweenPowerBuilderandothercomponents,suchasEJBcomponents,Javaclasses,andWebservices,aslongasthosecomponentscanbecalledfromC++.Tocreateamarshalerextension,buildaPBXthatcontainsatleastoneclassthatimplementstheIPBX_Marshalerinterface,aswellasoneormorenativeclasses.Theextensionmustcontaincodethatassociatesthemarshalerwithaproxyforthecomponentyouwanttocall.Ifyoubuildamarshalerextension,youshouldalsoprovideatoolthatgeneratesproxiessothecomponentscanbecalledfromPowerBuilder.Forexample,PowerBuilderprovidesamarshalerextensionforcallingEJBcomponentsfromPowerBuilder,anditprovidesatoolforgeneratingproxiesforEJBcomponents.ThischapterprovidesanoverviewbasedontheJavaMarshalersampleapplication,whichcanbedownloadedfromthePowerBuilderCodeSamplesWebsite,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:ImplementthecreatorclassStep3: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
Aboutthischapter
ThischapterdescribeshowPBNIextensionsexchangedatawithPowerBuilder.
Contents
Topic
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.
Helpermethods
TheIPB_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();
Setmethods
TheIPB_ValuesetmethodssetvaluesinthePBCallInfostructure.ThereisasetmethodforeachPowerBuilderdatatype:SetInt,SetUint,SetLong,SetUlong,andsoon.ThesemethodsautomaticallysetthevaluerepresentedbyIPB_Valuetonotnull.Thesyntaxis:virtualPBXRESULTSet<type>(<pbtype>arg);
Forexample,theSetLongmethodtakesanargumentoftypepblong.Inthisexample,themethodhastwointegerarguments,settoint_val1andint_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.
Getmethods
TheIPB_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.
Savingsimplevalues
Savingsimplevaluesisstraightforward.WhenyoucalloneoftheIPB_ValueGet<type>methodsforasimplevalue,suchasGetIntorGetReal,theactualdataisreturned.Asaresult,youcansimplysavethevaluesofanyofthefollowingdatatypes:
pbvalue_bytepbvalue_intpbvalue_uintpbvalue_longpbvalue_ulongpbvalue_realpbvalue_doublepbvalue_longlongpbvalue_booleanpbvalue_char
Savingpointervalues
Apointervaluedoesnotcontaindata.Itcontainsapointertoamemorylocationwherethedataisstored.WhenyoucalloneoftheIPB_ValueGet<type>methodsforapointervalue,suchasGetBloborGetTime,itreturnsapointertomemorythatisalsopointedtobyIPB_Value.WhenyoucallFreeCallInfo,thememorytowhichIPB_Valuepointsisreleasedandthedataisdeleted.Becausethisisthesamedatapointed
tobythepointerreturnedbytheGet<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.TheprocessingthattheAcquireArrayItemValueandReleaseValuemethodsperformresultsinpoorperformancewhenhandlinglargearrays.Itismoreefficienttogetthetypeofthearrayandhandleeach
typewithappropriatetype–specificfunctions.Caution
YoumustcalltheReleaseValuemethodtofreethedata.Ifyoudonotdoso,amemoryleakwilloccur.YoumustnotcallReleaseValuetoreleaseapointerthatwasnotacquiredusingAcquireValueandAcquireArrayItemValue.DoingsomightcausethePBVMtocrash.
Savingobjectvalues
Strictlyspeaking,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++
Aboutthischapter
Athird-partyapplicationorserverwritteninC++canloadthePowerBuilderVM,usePowerBuildernonvisualobjects,andusePowerBuildervisualcontrols.Thischapterusessomesimpleexamplestoillustratetheprocess.
Contents
Topic
AboutcallingPowerScriptfromC++applications
CallingPowerBuilderobjectsfromC++
Accessingresultsets
ProcessingPowerBuildermessagesinC++
MorePBNIpossibilities
AboutcallingPowerScriptfromC++applicationsIfyouhaveaPowerBuildercustomclassuserobjectthatperformsintensiveprogrammingthatwouldbeusefultoanapplicationthatyouneedtowriteinC++,youcanaccesstheobjectdirectlyfromtheC++applicationusingPBNI.YoudonotneedtomaketheuserobjectintoaCOMcomponentorautomationserver.TocallfunctionsonaPowerBuilderobject,youcanembedthePBVMintheC++application.TheC++applicationmustloadthePBVMbyloadingpbvm170.dllwiththeWindowsLoadLibraryfunction,getapointertotheIPB_VMinterfacebycallingthePB_GetVMfunctionexportedbypbvm170.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,youcangetthesignaturefromtheSystemTreeorwiththepbsig170tool.
GettingasignaturefromtheSystemTree
Togetthesignatureoff_multintheSystemTree,expandnvo_mult,right-clickonthef_multfunction,andselectPropertiesfromthepop-upmenu.ThesignaturedisplaysinthePropertiesdialogboxintheSignaturetextbox:
Gettingasignatureusingpbsig170
Togetthesignatureoff_multwithpbsig170,typethefollowingatacommandprompt:pbsig170d:\pbls\loadpbvm.pbl
Intheoutputofpbsig170,thecommentonthelastlinecontainsthesignaturetobepassedasthemethodIDargumenttoGetMethodID:PBObjectName:loadpbvm
PBObjectName:nvo_mult
publicfunctionintegerf_mult(integerarg1,
integerarg2)
/*III*/
Formoreinformationaboutthepbsig170toolandtheformatofmethodsignatures,seepbsig170.
CreatingtheC++applicationTocreatetheC++application,followthesesteps:1. LoadthePowerBuilderVM2. CallPB_GetVMtogetapointertotheIPB_VMinterface3. CreateanIPB_SessionobjectwithinIPB_VM4. CreateaninstanceofthePowerBuilderobject5. InitializethePBCallInfostructure6. CallthePowerBuilderfunction7. Writecleanupcode
LoadthePowerBuilderVM
InyourC++developmenttool,createanewconsoleapplicationproject.TheincludedirectoryforthePBNISDK,typicallyPowerBuilder15.0\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("pbvm170.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.
ProcessPBMessagemustbecalledrepeatedly
YouneedtomakesurethattheProcessPBMessagefunctioniscalledrepeatedly.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.
CallingProcessPBMessage
ThecalltoProcessPBMessageisinaloopintheWinMainfunction: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;
}
LoadingthePBVMandtriggeringanevent
IntheWndProcfunction,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("pbvm170.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;
}
TestingProcessPBMessage
YoucantesttheProcessPBMessagefunctionwithasimplePowerBuilderapplicationlikethisone: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.
WritinganextensionthatloadsthePBVM
MostoftheexamplesinthisbookandonthePowerBuilderCodeSamplesWebsiteshowyouhowtocreateanextensioninC++anduseitinPowerBuilder,orhowtowriteaC++applicationthatloadsthePowerBuilderVM.YoucouldalsowriteanextensionthatloadsthePowerBuilderVMandusesacustomclassuserobject,usingthetechniquesdescribedinthischapter.ThefollowingfiguredepictstheinteractionbetweenthePBVMandanexternalapplicationthatusesanextension.Figure5-2:InteractionbetweenPBNI,thePBVM,andexternalapplications
CallingPowerBuilderfromJava
YoucancombinetheabilitytocallPowerBuilderclassesfromC++,asdescribedinthischapter,withtheabilitytocreatemarshalerextensions,asdescribedinChapter3,"CreatingMarshalerExtensions,"tocallPowerBuilderfromJava.OnewaytodothisistocreateaJavaproxyclassthatdeclaresstaticnativemethodsthatcanbecalledtoloadthePBVM,createPowerBuildersessions,createPowerBuilderobjects,andinvokePowerScriptfunctions.ThesenativemethodscancallintothePBVMthroughPBNI.AdditionalJavaclassesthatrepresentthePBVM,PowerBuildersessions,andPowerBuilderobjectscanbebasedontheproxyclass.TheJavaclassescalltheJavanativemethodsthroughJNI,whereastheJavanativemethodscallPowerBuilderthroughPBNI.ThereisasamplethatillustratesthesetechniquesonthePowerBuilderCodeSamplesWebsite.
ReferenceThispartcontainsreferenceinformationforPBNIdatatypes,interfaces,andtools.
PBNITypesandReturnValues
Aboutthischapter
Thischaptercontainsinformationaboutthedatatypes,enumeratedtypes,anderrorreturnvaluesusedbythePowerBuilderNativeInterface.
Contents
Topic
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
EnumeratedtypesforPowerBuildergroups
Thepbgroup_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
EnumeratedtypesforPowerBuildervalues
Thepbvalue_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
EnumeratedtypesforPowerBuilderroutines
Thepbrt_typeenumeratedtypesareusedinIPB_SessionGetMethodIDcallstoidentifythetypeofroutinerequired.
Table6-5:EnumeratedtypesforPowerBuilderroutines
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
Aboutthischapter
Thischaptercontainsreferenceinformationabouttheclasses,structures,andmethodsofthePowerBuilderNativeInterface.
Contents
Topic
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.h
Theclasses,structures,andmethodsdefinedintheheaderfilepbni.hallowPowerBuilderextensionmodulestointeractwithPowerBuilder.Thisfilealsoincludesthepbarray.h,pbfield.h,andpbnimd.hheaderfiles.
pbarray.h,pbfield.h,pbtraits.h,andpbnimd.h
pbarray.hcontainshelperclassesthatmakeiteasiertocreatearraysandaccessdatainthem.pbfield.hcontainsahelperclassthatmakesiteasiertoaccessfields.Bothheaderfilesrelyonpbtraits.h,whichprovidesspecializationsfortheValueenumeratedtypes.pbnimd.hcontainsmachine-specificdatatypedefinitions.Thesefilesshouldnotbeincludeddirectlyinyourcode.
pbext.h
Theclasses,structures,andmethodsdefinedintheheaderfilepbext.hmustbeimplementedinPowerBuilderextensionmodulestoallowPowerBuilderapplicationstousetheextensionmodules.pbext.hincludespbni.handpbevtid.h.
pbevtid.h
pbevtid.hcontainsmappingsfromPowerBuildereventstringstointernaleventidentifiers.ThesemappingsallowthePBVMtoautomaticallyfireeventsthatyouincludeinthedescriptionofanextension.Formoreinformation,see"Eventprocessinginvisualextensions".
pbrsa.h
pbrsa.hcontainsstructuresandinterfacesusedtoaccessdatainDataStoresandDataWindowcontrols.
ClassandinterfacesummaryThistableliststheclassesandinterfacesthatmakeupPBNI.Afterthetable,theclassesandinterfacesarelistedinalphabeticalorder.Themethodsforeachclassarelistedinalphabeticalorderaftertheclassdescription.Severaladditionalhelperclassesthataredefinedinpbni.harenotlistedinthetable.Thesehelperclassesinclude:
PBArrayInfoHolderandPBCallInfoHolder–usedtoholdaPBArrayInfoorPBCallInfovariableandreleaseitwhenitisoutofscopePBEventTrigger,PBObjectFunctionInvoker,andPBGlobalFunctionInvoker–usedtotriggereventsandcallobjectandglobalfunctions
Table7-1:PBNIclassandinterfacesummary
Object Description Definedin
IPB_ArgumentsinterfaceUsedtoaccesstheargumentsofthePBCallInfostructure.
pbni.h
IPB_ResultSetAccessorinterface UsedtoaccessdatainaDataWindoworDataStore.
pbrsa.h
IPB_RSItemDatainterfaceUsedtosetdatavaluesinaresultsetfromaDataWindoworDataStore.
pbrsa.h
IPB_Sessioninterface
UsedtointeroperatewithPowerBuilder.Anabstractinterface,itdefinesmethodsforaccessingPowerScriptdata,callingPowerScriptfunctions,catchingandthrowingPowerScriptexceptions,
pbni.h
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
Usedtopassdataoftype
PB_TimeDatastructure TimeintheSetDatafunctionintheIPB_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,suchasEJBs,Javaclasses,
pbext.h
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
Description
TheIPB_ArgumentsandIPB_ValueinterfacesareusedtopassvaluesbetweenthePowerBuilderVMandPowerBuilderextensionmodules.EachargumentisrepresentedbyapointertotheIPB_Valueinterface.
Methods
TheIPB_Argumentsinterfacehastwomethods,GetAtandGetCount.
IPB_Argumentsinterface:
GetAtmethod
Description
ReturnsapointertotheIPB_Valueinterfacerepresentinganargumentwhoseorderinthelistofargumentsisindicatedbyaspecifiedindex.
SyntaxGetAt(pbintindex)
Argument Description
index AvalidindexintothePBCallInfostructure
ReturnValues
IPB_Value*.
Examples
Inthefollowingcodefragment,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);
}
SeeAlso
GetCount
IPB_Argumentsinterface:
GetCountmethod
Description
ObtainsthenumberofargumentsinaninstanceofPBCallInfo.
SyntaxGetCount()
ReturnValues
pbint.
Examples
ThisexampleusesGetCountinaFORloopusedtoprocessdifferentargumenttypes: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
Description
TheIPB_ResultSetAccessorinterfaceisusedtoaccessresultsetsinDataWindowandDataStoreobjects.
Methods
TheIPB_ResultSetAccessorinterfacehassixmethods:AddRefGetColumnCountGetColumnMetaDataGetItemDataGetRowCountRelease
IPB_ResultSetAccessorinterface:
AddRefmethod
Description
WhenyoucalltheCreateResultSetfunctionofinterfaceIPB_Session,youneedtopassanargumentoftypeIPB_ResultSetAccessor.TheAddReffunctioniscalledonthatargumentandtheReleasefunctioniscalledwhenthepbobjectisdestroyed.
SyntaxAddRef()
ReturnValues
None.
SeeAlso
CreateResultSetGetColumnCount
IPB_ResultSetAccessorinterface:
GetColumnCountmethod
Description
Obtainsthenumberofcolumns.
SyntaxGetColumnCount()
ReturnValues
Unsignedlong.
Examples
Thisstatementstoresthenumberofcolumnsin*numCols:*numCols=d_rsAccessor->GetColumnCount();
SeeAlso
CreateResultSetGetRowCount
IPB_ResultSetAccessorinterface:
GetColumnMetaDatamethod
Description
Obtainsacolumn'smetadata.Thecolumnnumberofthefirstcolumnis1.MemorymustbeallocatedforcolumnNamebeforethisfunctioncall.Thepointervaluescanbenull.
SyntaxGetColumnMetaData(unsignedlongcolumnNum,LPTSTRcolumnName,pbvalue_type*
Argument Description
columnNum Thenumberofthecolumnforwhichyouwanttoobtainmetadata
columnNameThenameofthespecifiedcolumn
type Apointertothetypeofthespecifiedcolumn
width Apointertothewidthofthespecifiedcolumn
ReturnValues
None.
Examples
Thisexamplegetsthenumberofcolumnsinaresultsetandallocatesanarraytoholdthetypesofeachcolumn: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;
}
}
SeeAlso
CreateResultSetGetColumnCountGetItemDataGetRowCount
IPB_ResultSetAccessorinterface:
GetItemDatamethod
Description
Accessesthedatainacell.Thefirstrowis1andthefirstcolumnis1.
SyntaxGetItemData(unsignedlongrow,unsignedlongcol,IPB_RSItemData*data
Argument Description
row Therownumberofthecell
col Thecolumnnumberofthecell
data ApointertoanIPB_RSItemDatastructure
ReturnValues
Boolean.
Examples
ThisexamplestoresthedatainthefirstrowandcolumnintheIPB_RSItemDatastructuresd:d_rsAccessor->GetItemData(1,1,&sd);
Usage
Ifthevalueofdataisnull,thisfunctionissuesthecallbackdata->SetNull.Ifthevalueisnotnull,itissuesthecallbackdata->SetData.Formoreinformation,examinetheIPB_RSItemDatainterface.
SeeAlso
CreateResultSetGetColumnCountGetColumnMetaDataGetRowCountIPB_RSItemDatainterface
SetDataSetNull
IPB_ResultSetAccessorinterface:
GetRowCountmethod
Description
Obtainsthenumberofrows.
SyntaxGetRowCount()
ReturnValues
Unsignedlong.
Examples
Thisstatementstoresthenumberofrowsin*numRows:*numRows=d_rsAccessor->GetRowCount();
SeeAlso
CreateResultSetGetColumnCountGetColumnMetaDataGetItemData
IPB_ResultSetAccessorinterface:
Releasemethod
Description
WhenyoucalltheCreateResultSetfunctionofinterfaceIPB_Session,youneedtopassanargumentoftypeIPB_ResultSetAccessor.TheAddReffunctioniscalledonthatargumentandtheReleasefunctioniscalledwhenthepbobjectisdestroyed.
SyntaxRelease()
ReturnValues
None.
SeeAlso
AddRefCreateResultSet
IPB_RSItemDatainterface
Description
TheIPB_RSItemDatainterfaceisusedasanargumenttotheGetItemDatafunctionofIPB_ResultSetAccessor.
Methods
TheIPB_RSItemDatainterfacehastwomethods:SetDataandSetNull.
IPB_RSItemDatainterface:
SetDatamethod
Description
SetsthedatainanIPB_RSItemDatastructurewhentheGetItemDatafunctionofIPB_ResultSetAccessoriscalledandthedatavalueisnotnull.
SyntaxSetData(unsignedlonglen,void*data)
Argument Description
len Thelengthofthedata
data Avoidpointertotheaddressofthedata
ReturnValues
None.
Usage
Ifthecelldatatypeis:stringanddecimal,theaddresspointstoastringdate,theaddresspointstoaPB_DateDatastructuretime,theaddresspointstoaPB_TimeDatastructuredatetime,theaddresspointstoaPB_DateTimeDatastructureanotherdatatype,theaddresspointstodataofthecorrespondingtype
SeeAlso
GetItemDataSetNullPB_DateDatastructurePB_DateTimeDatastructure
PB_TimeDatastructure
IPB_RSItemDatainterface:
SetNullmethod
Description
SetsthedatainanIPB_RSItemDatastructuretonullwhentheGetItemDatafunctionofIPB_ResultSetAccessoriscalledandthedatavalueisnotnull.
SyntaxSetNull()
ReturnValues
None.
SeeAlso
GetItemDataSetData
IPB_Sessioninterface
Description
TheIPB_SessioninterfaceisusedtointeroperatewithPowerBuilder.Anabstractinterface,itdefinesmethodsforaccessingPowerScriptdata,callingPowerScriptfunctions,catchingandthrowingPowerScriptexceptions,andsettingamarshalertoconvertPowerBuilderdataformatstotheuser'scommunicationprotocol.
Methods
Thistablelistsfunctionsbycategory.Fulldescriptionsinalphabeticorderfollowthetable.
Table7-2:IPB_Sessionmethodsbycategory
Purpose Method Description
Managingsessions Release
ReleasesthisIPBsession.TheIPB_Sessionobjectbecomesinvalidafterthecall.
Managingobjectreferences AddGlobalRef
AddsaglobalreferencetothespecifiedPowerBuilderobject.
AddLocalRefAddsalocalreferencetothespecifiedPowerBuilderobject.
NewObject Createsanewobjectofthespecifiedtype.
PopLocalFrame
Popsthecurrentlocalreferenceframefromthecurrentnativemethodstackframe.
Pushesalocalreference
PushLocalFrame frameontothecurrentnativemethodstackframe.
RemoveGlobalRef
RemovesaglobalreferencetothespecifiedPowerBuilderobject.
RemoveLocalRef
RemovesalocalreferencetothespecifiedPowerBuilderobject.
Managingsharedproperties GetProp
RetrievesapointertothedatavalueofavariablethathasbeenregisteredasasharedpropertyforthecurrentIPBsession.
RemoveProp
RemovesthespecifiedvariablefromthelistofpropertiesofthecurrentIPBsession.
SetProp
Addsanewvariabletothelistofpropertiesofthecurrentsessionorchangesthevalueofanexistingvariable.
HandlingthePowerBuildermessagequeue
ProcessPBMessage
ChecksthePowerBuildermessagequeueand,ifthereisamessageinthequeue,attemptstoprocessit.
Handlingexceptions ClearException
ClearsthecurrentPowerBuilderexception
object.
GetException Obtainsthecurrentthrownexceptionobject.
HasExceptionThrown
Checksfortheexistenceofanexceptionthathasbeenthrownbutnotcleared.
ThrowException
ThrowsaPowerBuilderexceptionorinheritedexception,replacingtheexistingexceptionifoneexists.
Passingarguments Add<type>Argument
AddsanargumentinavariableargumentPowerBuildercall.
FreeCallInfo FreesmemoryallocatedbyInitCallInfo.
InitCallInfo InitializesthePBCallInfostructure.
FindingPowerBuilderclassesandobjects
FindGroup
Searchesforagroupwithagivennameandgrouptypeinthecurrentlibrarylist.
FindClassSearchesforaclasswithagivennamewithinagivengroup.
FindClassByClassIDSearchesforaclasswithagivennameandagivenID.
Returnstheclasshandle
GetClass ofaPowerBuilderobject.
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.
SetSharedVarToNull Setsthevalueofasharedvariabletonull.
Workingwitharrays Get<type>ArrayItem
Returnsthevalueofanarrayitemofaspecificdatatype.
GetArrayInfo Obtainsinformationaboutanarray.
GetArrayItemType Obtainsthedatatypeofaniteminanarray.
GetArrayLength Returnsthelengthofanarray.
GetPBAnyArrayItem ObtainsthevalueofanarrayitemoftypeAny.
IsArrayItemNullReturnstrueifthearrayitemcontainsanarray,otherwisereturnsfalse.
NewBoundedSimpleArray Createsaboundedsimpledataarray.
NewUnboundedSimpleArray Createsanunboundedsimpledataarray.
NewBoundedObjectArrayCreatesaboundedPowerBuilderobjectorstructurearray.
NewUnboundedObjectArrayCreatesanunboundedPowerBuilderobjectorstructuredataarray.
ReleaseArrayInfoReleasesmemoryreturnedby
GetArrayInfo.
Set<type>ArrayItemSetsthevalueofanarrayitemofaspecificdatatype.
SetArrayItemToNull Setsthevalueofanarrayitemtonull.
Workingwithstrings GetStringLength
Returnsthelengthofastringinbyteswithouttheterminator.
GetStringReturnsapointertothestringpassedinasanargument.
NewString Createsanewstring.
ReleaseString Releasesthememoryusedbyastring.
SetStringFreesanexistingstringandassignsanewstringvaluetoit.
Workingwithbinarylargeobjects
GetBlob Returnsapointertothedatabufferforablob.
GetBlobLengthReturnsthelengthinbytesofblobdatainabuffer.
NewBlobCreatesanewblobandduplicatesabufferforthenewblobdata.
SetBlob
Destroystheexistingdatainabloband
copiesdataintoitfromabuffer.
Workingwithdecimalvalues GetDecimalString
Convertsdecimaldatainapbdecobjecttoastring.
NewDecimal Allocatesresourcesforanewdecimaldataobject.
ReleaseDecimalStringFreesthememoryacquiredusingGetDecimalString.
SetDecimal Convertsastringtoadecimal.
Workingwithdateandtimevalues GetDateString Convertsdataina
pbdateobjecttoastring.
GetDateTimeStringConvertsdatainapbdatetimeobjecttoastring.
GetTimeString Convertsdatainapbtimeobjecttoastring.
NewDate Createsanewpbdatedataobject.
NewDateTime Createsanewpbdatetimedataobject.
NewTime Createsanewpbtimedataobject.
ReleaseDateStringFreesthememoryacquiredusingGetDateString.
ReleaseDateTimeString FreesthememoryacquiredusingGetDateTimeString.
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>FieldAsetofdatatype-specificfunctions.Setsthevalueofaninstancefieldofanobject.
Set<type>Field
Asetofdatatype-specificfunctions.Setsthevalueofaninstancefieldofanobject.
UpdateFieldRefreshesavisualpropertyofaPowerBuilderobject.
Workingwithnativeclasses GetNativeInterface
Obtainsapointertotheinterfaceofanativeclass.
IsNativeObjectDetermineswhetherapbobjectisaninstanceofanativeclass.
AccessingresultsetsfromDataWindowsandDataStores
CreateResultSet
CreatesaresultsetobjectusingapointertoanIPB_ResultSetAccessorobject.
GetResultSetAccessor
Obtainsaninterfacethroughwhichyoucanreaddatafromaresultset.
ReleaseResultSetAccessorReleasesthepointerobtainedusing
GetResultSetAccessor.
Workingwithmarshalerextensions
GetMarshalerObtainsthemarshalerobjectassociatedwithaproxyobject.
NewProxyObject Createsaproxyforaremoteobject.
SetMarshaler
SetsamarshalerthatwillbeusedtoinvokeremotemethodsandconvertPowerBuilderdataformatstotheuser'scommunicationprotocol.
IPB_Sessioninterface:
AcquireArrayItemValuemethod
Description
ClonesthedatainthePBCallInfostructureinanarrayitemandresetstheIPB_Valuepointer.
SyntaxAcquireArrayItemValue(pbarrayarray,pblongdim[])
Argument Description
array Avalidpbarraystructure.
dimApblongarraytoholdtheindexesofalldimensionsofthearray.Thesizeofthearraymustequalthedimensionsofarray.
ReturnValues
IPB_Value*.
Examples
ThisFORloopacquiresthevalueofaniteminanarrayandsetsthevalueinanotherarray:for(i=1;i<=bound;i++)
{
dim[0]=i;
ipv=Session->AcquireArrayItemValue(refArg,dim);
Session->SetArrayItemValue(*i_array,dim,ipv);
Session->ReleaseValue(ipv);
}
Usage
TheAcquireArrayItemValuemethodenablesyoutoretainthedatainthePBCallInfostructureforasinglearrayitem.TheAcquireArrayItemValuemethodisindependentofthetypeofthedatabutismostusefulforacquiringthevalueofpointervalues,suchaspbvalue_string,pbvalue_blob,andsoon.WhenyoucallFreeInfo,the
dataisnotfreedandthepointerreturnedbyAcquireArrayItemValueisstillvalid.Whenyounolongerneedthedata,youmustcalltheReleaseValuemethodtofreethedata.Failingtodosocausesamemoryleak.ThePBVMclonesanewIPB_Valueandresetstheexistingone.Ifyouattempttogetoracquiretheoriginalvalue,thevaluereturnediszeroornulluntilanotherIPB_Valueissettothevalue.Workingwithlargearrays
TheprocessingthattheAcquireArrayItemValueandReleaseValuemethodsperformresultsinpoorperformancewhenhandlinglargearrays.Itismoreefficienttogetthetypeofthearrayandhandleeachtypewithappropriatetype–specificfunctions.
SeeAlso
ReleaseValue
IPB_Sessioninterface:
AcquireValuemethod
Description
ClonesthedatainthePBCallInfostructureandresetstheIPB_Valuepointer.
SyntaxAcquireValue(IPBValue*value)
Argument Description
value Thevaluetobereturned
ReturnValues
IPB_Value*.
Examples
TheAcquireValuemethodisusedtoobtainamessageargumentvalue.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);
}
Usage
TheAcquireValuemethodenablesyoutoretainthedatainthePBCallInfostructure.TheAcquireValuemethodisindependentofthetypeofthedatabutismostusefulforacquiringthevalueofpointervaluessuchaspbvalue_string,pbvalue_blob,andsoon.WhenyoucallFreeInfo,thedataisnotfreedandthepointerreturnedbyAcquireValue
isstillvalid.Ifthevalueacquiredisanarray,theentirearrayisacquired.Toacquireasingleelementinanarray,usetheAcquireItemValuemethod.Whenyounolongerneedthedata,youmustcalltheReleaseValuemethodtofreethedata.Failingtodosocausesamemoryleak.ThePBVMclonesanewIPB_Valueandresetstheexistingone.Ifyouattempttogetoracquiretheoriginalvalue,thevaluereturnediszeroornulluntilanotherIPB_Valueissettothevalue.
SeeAlso
AcquireArrayItemValueReleaseValue
IPB_Sessioninterface:
Add<type>Argumentmethod
Description
AddsanargumentofaspecifictypeinavariableargumentPowerBuildercall.
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.
ReturnValues
PBXRESULT.PBX_OKonsuccess.
Examples
ThiscodeteststhataddinganintegerargumenttoaPBCallInfostructureciworkscorrectly: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;
}
Usage
ThiscallisusedinvariableargumentPowerBuildercalls,suchasdatawindow.retrieve(arg).Afterthecall,thevaluereturnedbyci->pArgs->GetCount()increasesbyone.
SeeAlso
GetCountInvokeClassFunction
InvokeObjectFunction
IPB_Sessioninterface:
AddGlobalRefmethod
Description
AddsaglobalreferencetothespecifiedPowerBuilderobject.
SyntaxAddGlobalRef(pbobjectobj)
Argument Description
obj AvalidPowerBuilderobjecthandle
ReturnValues
pbclassornullonerror.
Examples
Thisexamplecheckswhetherareturnvalueisnull,andifitisnot,addsaglobalreferencetoittothesession:if(ci->returnValue->IsNull())
ret_val=0;
else
{
ret_val=ci->returnValue->GetObject();
Session->AddGlobalRef(ret_val);
}
SeeAlso
RemoveGlobalRef
IPB_Sessioninterface:
AddLocalRefmethod
Description
AddsalocalreferencetothespecifiedPowerBuilderobject.
SyntaxAddLocalRef(pbobjectobj)
Argument Description
obj AvalidPowerBuilderobjecthandle
ReturnValues
pbclassornullonerror.
Examples
Thisexampledefinesfunctionsthataddandremovelocalreferences:voidMyPBNIClass::reference()
{
d_session->AddLocalRef(d_pbobject);
}
voidMyPBNIClass::unreference()
{
if(d_pbobject!=NULL)
d_session->RemoveLocalRef(d_pbobject);
}
SeeAlso
PopLocalFramePushLocalFrameRemoveLocalRef
IPB_Sessioninterface:
ClearExceptionmethod
Description
ClearsthecurrentPowerBuilderexceptionobject.
SyntaxClearException()
ReturnValues
None.
Usage
HasExceptionThrownreturnsfalseafteracalltoClearException.Ifnoexceptionhasbeenthrown,thiscallhasnoeffect.
SeeAlso
GetExceptionHasExceptionThrownThrowException
IPB_Sessioninterface:
CreateResultSetmethod
Description
CreatesaresultsetobjectusingapointertoanIPB_ResultSetAccessorobject.
SyntaxCreateResultSet(IPB_ResultSetAccessor*rs)
Argument Description
rs ApointertoanIPB_ResultSetAccessorobject
ReturnValues
pbobject.
Examples
ThisexampleloadsthePBVMandcallsthef_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("pbvm170.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
//ProfilePBDemoDBV170
SQLCA.DBMS="ODBC"
SQLCA.AutoCommit=False
SQLCA.DBParm=&
"ConnectString='DSN=PB
DemoDBV170;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
Usage
TousetheIPB_ResultSetAccessorinterface,loadthePBVM,obtainaresultsetfromaPowerBuilderapplication,andcallGetResultSetAccessoronthisresultsettogetanIPB_ResultSetAccessorinterfaceobject.Youcanthencallthemethods
ofthisobjecttogetinformationabouttheresultset.YoucanalsocallCreateResultSetusingthisobjectasanargumenttocreatearesultsetthatyoucanreturntoPowerBuilder.WhenyoucallCreateResultSet,theAddReffunctionoftheIPB_ResultSetAccessorinterfaceiscalledonthersargumentimplicitlytoaddareferencetotheinterfacepointer.
SeeAlso
AddRefGetResultSetAccessorIPB_ResultSetAccessorinterfaceReleaseResultSetAccessor
IPB_Sessioninterface:
FindClassmethod
Description
Searchesforaclasswithagivennamewithinagivengroup.
SyntaxFindClass(pbgroupgroup,LPCTSTRname)
Argument Description
group Thehandleofthegroupinwhichtheclassresides
name Theclassnameinlowercase
ReturnValues
pbclassornullonfailure.
Examples
Thisexamplefindsthegroupassociatedwiththef_getrowfunctionandusesthegrouptofindtheclass:group=session->FindGroup("f_getrow",
pbgroup_function);
if(group==NULL)
return;
cls=session->FindClass(group,"f_getrow");
if(cls==NULL)
return;
Usage
ThismethodsearchesforaPowerBuilderclasswiththegivennameinthegivengroup.Forexample,inawindowdefinitionw_1,w_1isagroup,andw_1andcontrolscontainedinitareallclassesofgroupw_1.
SeeAlso
FindGroupNewObject
IPB_Sessioninterface:
FindClassByClassIDmethod
Description
SearchesforaclasswithagivennameandagivenID.
SyntaxFindClass(pbgroupgroup,pbintclassID)
Argument Description
group Thehandleofthegroupinwhichtheclassresides
classID Theclassnameinlowercase
ReturnValues
pbclassornullonfailure.
Usage
ThismethodsearchesforaPowerBuilderclasswiththegivennameandthegivenID.
SeeAlso
FindGroupNewObject
IPB_Sessioninterface:
FindGroupmethod
Description
Searchesforagroupwithagivennameandgrouptypeinthecurrentlibrarylist.
SyntaxFindGroup(LPCTSTRname,pbgroup_typetype)
Argument Description
name Thegroupnameinlowercase
type Anenumeratedtypedefinedinpbgroup_type
ReturnValues
pbgroupornullonfailure.
Examples
Thisexamplefindsthegroupassociatedwithuser_exceptionandusesthegrouptofindtheclass:group=session->FindGroup("user_exception",
pbgroup_userobject);
if(group==NULL)
return;
cls=session->FindClass(group,"user_exception")
SeeAlso
FindClassNewObject
IPB_Sessioninterface:
FindMatchingFunctionmethod
Description
Findsafunctionthathasthespecifiedargumentlist.
SyntaxFindMatchingFunction(pbclasscls,LPCTSTRmethodName,PBRoutineType
Argument Description
cls pbclasscontainingthemethod.
methodName Thestringnameofthemethodinlowercase.
rt Typeofthemethod:PBRT_FUNCTIONforfunctionorPBRT_EVENTforevent.
readableSignature
Acomma-separatedstringlistingthetypesofthemethod'sarguments.Thereturntypeofthemethodisnotincludedinthestring.SeetheUsagesectionforexamples.
ReturnValues
pbmethodID.
Examples
ThisexamplereturnsthemethodIDofafunctionnameduf_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);
Usage
FindMatchingFunctionprovidesanalternativetotheGetMethodIDfunction.Itrequiresalistofthefunction'sarguments(thereadableSignature)insteadofthesignatureobtainedusingthepbsig170tool.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.
SeeAlso
GetMethodID
IPB_Sessioninterface:
FreeCallInfomethod
Description
FreesmemoryallocatedbyInitCallInfo.
SyntaxFreeCallInfo(PBCallInfo*ci)
Argument Description
ci ApointertothepreallocatedPBCallInfostructure
ReturnValues
None.
Examples
FreeCallInfoshouldbecalledwhenthePBCallInfostructureisnolongerneeded:Session->InvokeObjectFunction(myobj,mid,ci);
ret_val=ci.returnValue->GetInt();
Session->FreeCallInfo(ci);
deleteci;
returnret_val;
Usage
ThismethodfreesmemoryallocatedbyInitCallInfobutdoesnotfreethestructureciitself.
SeeAlso
InitCallInfo
IPB_Sessioninterface:
Get<type>ArrayItemmethod
Description
Obtainsthevalueofanarrayitemofaspecifiedtype.
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.
Examples
Thisexamplegetsthevalueofanarrayitemoftypepbobject:pbobjectpPBObject=NULL;
pbbooleanbIsNull=0;
pblongdim[1];
dim[0]=pbl+1;
pPBObject=session->GetObjectArrayItem(array,dim,
bIsNull);
SeeAlso
GetArrayInfoGetArrayItemTypeGetArrayLengthIsArrayItemNullNewBoundedObjectArrayNewBoundedSimpleArrayNewUnboundedObjectArrayNewUnboundedSimpleArrayReleaseArrayInfoSetArrayItemToNullSetArrayItemValueSet<type>ArrayItem
IPB_Sessioninterface:
Get<type>Fieldmethod
Description
Asetofmethodsthatgetsthevalueofaninstancefieldofanobject.
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
ReturnValues
ApredefinedPBNIdatatypethatcorrespondstothePowerBuilderdatatypeinthemethodname.
Examples
Thisexamplegetsthevalueofafieldoftypepbstring:pbbooleanisNull;
pbstringpstr=
session->GetStringField(proxy,fid,isNull);
if(pstr!=NULL)
{
myclass=session->GetString(pstr);
//processmyclass
}
SeeAlso
GetFieldIDGetFieldTypeGetNumOfFieldsIsFieldArrayIsFieldNullIsFieldObjectSetFieldToNullSet<type>Field
IPB_Sessioninterface:
Get<type>GlobalVarmethod
Description
Asetofmethodsthatgetsthevalueofaglobalvariableofaspecificdatatype.
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
ApredefinedPBNIdatatypethatcorrespondstothePowerBuilder
datatypeinthemethodname.
Examples
ThiscodegetsthevalueofaglobalvariableofdatatypelongusingitsfieldID:fid=session->GetGlobalVarID("l_gvar");
l_val=session->GetLongGlobalVar(fid,isNull);
session->SetLongGlobalVar(fid,l_val+1);
SeeAlso
GetGlobalVarIDGetGlobalVarTypeIsGlobalVarArrayIsGlobalVarNullIsGlobalVarObjectSetGlobalVarToNullSet<type>GlobalVar
IPB_Sessioninterface:
Get<type>SharedVarmethod
Description
Asetofmethodsthatgetsthevalueofasharedvariableofaspecificdatatype.
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
ReturnValues
ApredefinedPBNIdatatypethatcorrespondstothePowerBuilderdatatypeinthemethodname.
Examples
Thiscodegetsthevalueofasharedvariableoftypeinteger: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);
SeeAlso
GetSharedVarIDGetSharedVarTypeIsSharedVarArrayIsSharedVarNullIsSharedVarObjectSet<type>SharedVarSetSharedVarToNull
IPB_Sessioninterface:
GetArrayInfomethod
Description
Obtainsinformationaboutanarray.
SyntaxGetArrayInfo(pbarrayarray)
Argument Description
array Avalidarrayhandle
ReturnValues
PBArrayInfo*.
Examples
ThisIF-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;
}
Usage
Ifthearrayisanunboundedarray,theboundsinformationinPBArrayInfoisundetermined.ThereturnedPBArrayInfomustbefreedlaterbyReleaseArrayInfo.
SeeAlso
Get<type>ArrayItemGetArrayItemType
GetArrayLengthIsArrayItemNullNewBoundedObjectArrayNewBoundedSimpleArrayNewUnboundedObjectArrayNewUnboundedSimpleArrayReleaseArrayInfoSetArrayItemToNullSetArrayItemValueSet<type>ArrayItem
IPB_Sessioninterface:
GetArrayItemTypemethod
Description
Obtainsthedatatypeofaniteminanarray.
SyntaxGetArrayItemType(pbarrayarray,pblongdim[])
Argument Description
array Avalidpbarraystructure.
dimApblongarraytoholdtheindexesofeachdimensionofthearray.Thesizeofthearraymustequalthedimensionsofarray.
ReturnValues
pbuint.
SeeAlso
Get<type>ArrayItemGetArrayInfoGetArrayLengthIsArrayItemNullNewBoundedObjectArrayNewBoundedSimpleArrayNewUnboundedObjectArrayNewUnboundedSimpleArrayReleaseArrayInfoSetArrayItemToNullSetArrayItemValueSet<type>ArrayItem
IPB_Sessioninterface:
GetArrayLengthmethod
Description
Obtainsthelengthofanarray.
SyntaxGetArrayLength(pbarrayarray)
Argument Description
array Avalidarrayhandle
ReturnValues
pblong.
Examples
ThisIF-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;
}
SeeAlso
Get<type>ArrayItemGetArrayInfoIsArrayItemNullNewBoundedObjectArrayNewBoundedSimpleArray
NewUnboundedObjectArrayNewUnboundedSimpleArrayReleaseArrayInfoSetArrayItemToNullSetArrayItemValueSet<type>ArrayItem
IPB_Sessioninterface:
GetBlobmethod
Description
Returnsapointertothedatabufferforablob.
SyntaxGetBlob(pbblobbin)
Argument Description
bin Apointertothesourcebuffer
ReturnValues
void*.
Examples
InthisCASEclause,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;
SeeAlso
GetBlobLengthNewBlobSetBlob
IPB_Sessioninterface:
GetBlobLengthmethod
Description
Returnsthelengthinbytesofblobdatainabuffer.
SyntaxGetBlobLength(pbblobbin)
Argument Description
bin Apointertothesourcebuffer
ReturnValues
pblong.
Examples
Inthisexample,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);
SeeAlso
GetBlobNewBlobSetBlob
IPB_Sessioninterface:
GetClassmethod
Description
ReturnstheclasshandleofaPowerBuilderobject.ThisfunctionismostfrequentlyusedtoobtainaclasshandleforusewiththeGetMethodIDfunction.
SyntaxGetClass(pbobjectobj)
Argument Description
obj AvalidPowerBuilderobjecthandle
ReturnValues
pbclassornullonerror.
Examples
Inthisexample,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;
}
SeeAlso
GetClassNameGetMethodID
IPB_Sessioninterface:
GetClassNamemethod
Description
Returnsthenameofaclassinlowercase.
SyntaxGetClassName(pbclasscls)
Argument Description
cls Avalidclasshandle
ReturnValues
LPCTSTR.
Examples
ThisexamplegetsthenameofaclassandsetsthesizeofthevariablestLengthtothelengthofthereturnedstringplus1:LPCTSTRmyClassName=session->GetClassName(myClass);
size_tstLength=strlen((LPSTR)myClassName)+1;
Usage
Whenyouhavefinishedusingthename,calltheReleaseStringmethodtofreethememoryacquired.
SeeAlso
GetClassReleaseString
IPB_Sessioninterface:
GetCurrGroupmethod
Description
Obtainsthenameofthecurrentgroup.
SyntaxGetCurrGroup()
ReturnValues
pbgroupornullonfailure.
Examples
Thisexamplegetsthenameofthecurrentgroupandusesittoobtaintheidentifierofasharedvariable,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);
SeeAlso
Get<type>SharedVarGetSharedVarIDSet<type>SharedVar
IPB_Sessioninterface:
GetDateStringmethod
Description
Convertsdatainapbdateobjecttoastring.
SyntaxGetDateString(pbdatedate)
Argument Description
date Thepbdatedataobjecttobeconvertedtoastring.
ReturnValues
LPCTSTR.
SeeAlso
NewDateReleaseDateStringSetDate
IPB_Sessioninterface:
GetDateTimeStringmethod
Description
Convertsdatainapbdatetimeobjecttoastring.
SyntaxGetDateTimeString(pbdatetimedatetime)
Argument Description
datetime Thepbdatetimedataobjecttobeconvertedtoastring.
ReturnValues
LPCTSTR.
SeeAlso
NewDateTimeReleaseDateTimeStringSetDateTime
IPB_Sessioninterface:
GetDecimalStringmethod
Description
Convertsdecimaldatainapbdecobjecttoastring.
SyntaxGetDecimalString(pbdecdec)
Argument Description
dec Thepbdecdataobjecttobeconvertedtoastring.
ReturnValues
LPCTSTR.
Examples
ThiscodecheckswhetheravalueinthePBCallInfostructureisnull.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;
SeeAlso
NewDecimalReleaseDecimalStringSetDecimal
IPB_Sessioninterface:
GetEnumItemNamemethod
Description
Obtainsthenameofanenumeratedvariable.
SyntaxGetEnumItemName(LPCTSTRenumName,longenumItemValue)
ReturnValues
LPCTSTR.
Usage
Whenyouhavefinishedusingthename,calltheReleaseStringmethodtofreethememoryacquired.
SeeAlso
GetEnumItemValueReleaseString
IPB_Sessioninterface:
GetEnumItemValuemethod
Description
Obtainsthevalueofanenumeratedvariable.
SyntaxGetEnumItemValue(LPCTSTRenumName,LPCTSTRenumItemName)
ReturnValues
Long.
Examples
Thisexamplegetsthenumericvaluefortheboolean!enumeratedvalue,thenusesittoreturnthestringvalue:pblonglType=session->GetEnumItemValue("object",
boolean");//returns138
LPCTSTRszEnum=session->GetEnumItemName("object",
lType);//returns"boolean"
Usage
GetEnumItemValueandGetEnumItemNamesupportenumeratedtypes.Theyallowyoutoconvertthenameofanenumeratedvalue,astringwithanappendedexclamationmark(!),toanintegervalue,andviceversa.The!charactermustbeomitted
Whenyouusethesefunctions,theenumItemNameshouldnotusetheappendedexclamationmark(!)character.ToreturnanenumeratedvaluefromanextensiontoPowerScript,youmustusetheSetLongfunctiontosetthevalueoftheenumeratedvariableintoIPB_Value.UsingSetIntorSetShortfails.However,youcanuseGetIntorGetShortaswellasGetLongtoobtaintheenumeratedvariable'svalue,assumingthevalueisintheappropriaterange.Forexample,ifyouattempttouseGetInttoobtainavaluethatismorethan32767,thereturnedvalueistruncated.
SeeAlso
GetEnumItemName
IPB_Sessioninterface:
GetExceptionmethod
Description
Obtainsthecurrentthrownexceptionobject.
SyntaxGetException()
ReturnValues
pbobject.
Examples
Thiscodegetsthecurrentexceptionobject,clearstheexception,andgetstheclassoftheexceptionobject:pbclasscls;
pbobjectex;
...
ex=session->GetException();
session->ClearException();
cls=session->GetClass(ex);
SeeAlso
ClearExceptionHasExceptionThrown
IPB_Sessioninterface:
GetFieldIDmethod
Description
ObtainstheinternalIDofaclassinstancevariable.
SyntaxGetFieldID(pbclasscls,LPCTSTRfieldName)
Argument Description
cls Theclassinwhichthefieldresides
fieldName Theinstancemembername,inlowercase
ReturnValues
pbfieldIDor0xffffifafieldIDcannotbefound.
Examples
Thisfunctionobtainstheidentifierofaclass'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;
}
Usage
GetFieldIDisoneofasetoffunctionsthatallowsnativecodetoaccessthefieldsofJavaobjectsandgetandsettheirvalues.YouuseGetFieldIDtoretrievethevalueofafield,specifyingtheclassnameandthefieldname.ThefieldIDreturnedcanbeusedasanargumenttotherelatedfunctions.
SeeAlso
GetFieldTypeGet<type>FieldGetNumOfFieldsIsFieldArrayIsFieldNullIsFieldObjectSet<type>FieldSetFieldToNull
IPB_Sessioninterface:
GetFieldNamemethod
Description
Obtainsthenameofthespecifiedfield.
SyntaxGetFieldName(pbclasscls,pbfieldIDfid)
Argument Description
cls Theclassthatdefinesthefield
fid TheinternalIDoftheclassinstancevariable
ReturnValues
LPCTSTR.Thefieldnameofthespecifiedfield.IfanincorrectfieldIDisspecified,thisfunctionreturnsnull.
Usage
Whenyouhavefinishedusingthename,calltheReleaseStringmethodtofreethememoryacquired.
SeeAlso
GetFieldIDReleaseString
IPB_Sessioninterface:
GetFieldTypemethod
Description
Obtainsthedatatypeofafielddeclaredbyaclass.
SyntaxGetFieldType(pbclasscls,pbfieldIDfid)
Argument Description
cls Theclassthatdefinesthefield
fid TheinternalIDoftheclassinstancevariable
ReturnValues
pbint.Asimpledatatypedefinedinthelistofpbvalue_typeenumeratedtypes,suchaspbvalue_int.See"PBNIenumeratedtypes".
Examples
ThisstatementgetsthetypeofthespecifiedfieldID:pbintpbfieldType=session->GetFieldType(cls,fid);
SeeAlso
GetFieldIDGet<type>FieldGetNumOfFieldsIsFieldArrayIsFieldNullIsFieldObjectSet<type>FieldSetFieldToNull
IPB_Sessioninterface:
GetGlobalVarIDmethod
Description
ReturnstheinternalIDofaglobalvariable.
SyntaxGetGlobalVarID(LPCTSTRname)
Argument Description
name Thenameoftheglobalvariableinlowercase
ReturnValues
pbfieldIDornullonfailure.
Examples
Thisexamplegetstheinternalidentifierofalongvariableandusesittogetandsetaglobalvariable:fid=session->GetGlobalVarID("l_gvar");
l_val=session->GetLongGlobalVar(fid,isNull);
session->SetLongGlobalVar(fid,l_val+1);
SeeAlso
GetGlobalVarTypeGet<type>GlobalVarIsGlobalVarArrayIsGlobalVarNullIsGlobalVarObjectSetGlobalVarToNullSet<type>GlobalVar
IPB_Sessioninterface:
GetGlobalVarTypemethod
Description
Obtainsthedatatypeofaglobalvariable.
SyntaxGetGlobalVarType(pbfieldIDfid)
Argument Description
fid TheinternalIDoftheclassinstancevariable
ReturnValues
pbuint.Asimpledatatypedefinedinthelistofpbvalue_typeenumeratedtypes.
Examples
ThiscodetestsgettingandsettingaglobalintegervariableusingthefieldIDfid:fid=session->GetGlobalVarID("i_gvar");
if(session->GetGlobalVarType(fid)==pbvalue_int)
{
i_val=session->GetIntGlobalVar(fid,isNull);
session->SetIntGlobalVar(fid,i_val+1);
}
SeeAlso
GetGlobalVarIDGet<type>GlobalVarIsGlobalVarArrayIsGlobalVarNullIsGlobalVarObjectSetGlobalVarToNullSet<type>GlobalVar
IPB_Sessioninterface:
GetMarshalermethod
Description
Obtainsthemarshalerobjectassociatedwithaproxyobject.
SyntaxGetMarshaler(pbproxyObjectobj)
Argument Description
obj AnobjectoftypepbproxyObjectforwhichyouwanttofindthemarshaler.
ReturnValues
IPBX_Marshaler*.
Examples
ThiscodecreatesaJavamarshalerobjectandassociatesitwithaproxy.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);
SeeAlso
SetMarshaler
IPB_Sessioninterface:
GetMethodIDmethod
Description
ReturnstheIDoftherequestedmethod.
SyntaxGetMethodID(pbclasscls,LPCTSTRmethodName,PBRoutineTypert,LPCTSTR
Argument Description
cls pbclasscontainingthefunction.
methodNameThestringnameofthemethodinlowercase.
rt Typeofthemethod:PBRT_FUNCTIONforfunctionorPBRT_EVENTforevent.
signature
InternalsignatureofthePowerBuilderfunction,usedtoidentifypolymorphicmethodsinoneclass.Obtainedwiththepbsig170tool.Ifthesignatureisanullstring(""),thefirstmethodfoundwiththenamemethodNameisreturned.
publicOnlyAbooleanthatdetermineswhetheronlypublicmethodsaresearched(true)orallmethodsaresearched(false).Thedefaultistrue.
ReturnValues
pbMethodIDofthemethodorkUndefinedMethodIDonerror.
Examples
ThisfunctionusesGetMethodIDtoobtaintheidentifier(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;
}
Usage
TheGetMethodIDfunctionisusedtoobtaintheIDofamethodsoyoucanuseittoinvokefunctionsandtriggerevents.
SeeAlso
FindMatchingFunctionInvokeObjectFunctionTriggerEvent"CallingPowerScriptfromanextension"
IPB_Sessioninterface:
GetMethodIDByEventIDmethod
Description
ReturnstheIDofthemethodthathasagivenpredefinedPowerBuildereventID.
SyntaxGetMethodIDByEventID(pbclasscls,LPCTSTReventID)
Argument Description
cls pbclasscontainingthemethod
eventID APowerBuilderpredefinedeventstring,suchaspbm_bnclicked
ReturnValues
pbMethodIDofthemethodorkUndefinedMethodIDonerror.
Examples
ThisstatementobtainstheIDoftheeventidentifiedbythenamepbm_lbuttonup:pbmethodIDmid=d_session->GetMethodIDByEventID(clz,
"pbm_lbuttonup");
SeeAlso
GetMethodID
IPB_Sessioninterface:
GetNativeInterfacemethod
Description
Obtainsapointertotheinterfaceofanativeclass.
SyntaxGetNativeInterface(pbobjectobj)
Argument Description
obj Avalidobjecthandle
ReturnValues
IPBX_UserObject.
Examples
Thisexampleinvokesthefunctionf_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;
}
Usage
UsethismethodinconjunctionwithIsNativeObjecttoobtainadirectreferencetotheIPBX_UserObjectassociatedwithanativeclassinthesamePowerBuilderextension.Theclassanditsmethodscanthenbeaccesseddirectly.
SeeAlso
IsNativeObject
IPB_Sessioninterface:
GetNumOfFieldsmethod
Description
Returnsthenumberoffieldsinthespecifiedclass.
SyntaxGetNumOfFields(pbclasscls)
Argument Description
cls Avalidclasshandlefortheclasswhosefieldistobeaccessed
ReturnValues
pbulong.
Examples
Thiscodegetsthenumbersoffieldsintheclassclz:pbclassclz=d_session->GetClass(d_pbobj);
pbulongnf=d_session->GetNumOfFields(clz);
SeeAlso
GetFieldIDGet<type>FieldIsFieldArrayIsFieldNullIsFieldObjectSetFieldToNullSet<type>Field
IPB_Sessioninterface:
GetPBAnyArrayItemmethod
Description
ObtainsthevalueofaglobalvariableoftypeAny.
SyntaxGetPBAnyArrayItem(pbarrayarray,pblongdim[],pbboolean&isNull)
Argument Description
array Avalidpbarraystructure.
dimApblongarraytoholdtheindexesofeachdimensionofthearray.Thesizeofthearraymustequalthedimensionsofarray.
isNull Indicateswhetherthevariableisnull
ReturnValues
IPB_Value*.
Usage
SeeGetPBAnyField.
SeeAlso
GetPBAnyFieldGetPBAnyGlobalVarGetPBAnySharedVar
IPB_Sessioninterface:
GetPBAnyFieldmethod
Description
ObtainsthevalueofavariableoftypeAny.
SyntaxGetPBAnyField(pbobjectobj,pbfieldIDfid,pbboolean&isNull)
Argument Description
obj Avalidobjecthandlefortheobjectwhosevalueistobeobtained
fid ThefieldIDofthevariable
isNull Indicateswhetherthevariableisnull
ReturnValues
IPB_Value*.
Examples
ThisexampletestsallthefunctionsusedtogetthevalueofvariablesoftypeAny,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();
Usage
ThevalueyouretrievemustbeofdatatypeAnytousethisfunction;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,usetheIPB_ValueGetTypefunctiontogetitsdatatypefirst,thenusetheappropriategetfunctiontogetitsvalue.
IPB_ValueholdsareferencetotheoriginalvalueThevalueintheIPB_Valueinstanceisareferencetotheoriginalvalue.IfyouchangetheactualvalueofthereturnedIPB_Value,theoriginalvalueisalsochanged.IfyouusetheAcquireValuefunctiontosavethevalue,itclonesanewIPB_ValueandresetstheexistingIPB_Valuepointer.
SeeAlso
GetPBAnyArrayItemGetPBAnyGlobalVarGetPBAnySharedVar
IPB_Sessioninterface:
GetPBAnyGlobalVarmethod
Description
ObtainsthevalueofaglobalvariableoftypeAny.
SyntaxGetPBAnyGlobalVar(pbfieldIDfid,pbboolean&isNull)
Argument Description
fid ThefieldIDofthevariable
isNull Indicateswhetherthevariableisnull
ReturnValues
IPB_Value*.
Usage
SeeGetPBAnyField.
SeeAlso
GetPBAnyArrayItemGetPBAnyFieldGetPBAnySharedVar
IPB_Sessioninterface:
GetPBAnySharedVarmethod
Description
ObtainsthevalueofasharedvariableoftypeAny.
SyntaxGetPBAnySharedVar(pbgroupgroup,pbfieldIDfid,pbboolean&isNull)
Argument Description
group Thegrouptowhichthevariablebelongs
fid ThefieldIDofthevariable
isNull Indicateswhetherthevariableisnull
ReturnValues
IPB_Value*.
Usage
SeeGetPBAnyField.
SeeAlso
GetPBAnyArrayItemGetPBAnyFieldGetPBAnyGlobalVar
IPB_Sessioninterface:
GetPropmethod
Description
RetrievesapointertothedatavalueofavariablethathasbeenregisteredasasharedpropertyforthecurrentIPBsession.
SyntaxGetProp(LPCTSTRname)
Argument Description
name Thenameofthevariablewhosevalueistoberetrieved.
ReturnValues
Void*.Ifthevariabledoesnotexist,returnsnull.
Examples
SeeSetProp.
Usage
Thevariable'snamemustfirstberegisteredwiththesessionusingtheSetPropfunction.
SeeAlso
RemovePropSetProp
IPB_Sessioninterface:
GetResultSetAccessormethod
Description
Obtainsaninterfacethroughwhichyoucanreaddatafromaresultset.
SyntaxGetResultSetAccessor(pbobjectrs)
Argument Description
rs ApbobjectholdingaresultsetobtainedusingCreateResultSet
ReturnValues
IPB_ResultSetAccessor
Examples
Thisexamplegetsaresultset,rs,fromthereturnvalueofaPowerScriptfunctionandusesittocreateanIPB_ResultSetAccessorobject,rsa:pbobjectrs=ci.returnValue->GetObject();
IPB_ResultSetAccessor*rsa=
session->GetResultSetAccessor(rs);
SeeAlso
CreateResultSetReleaseResultSetAccessor
IPB_Sessioninterface:
GetSharedVarIDmethod
Description
ReturnstheinternalIDofasharedvariable.
SyntaxGettSharedVarID(pbgroupgroup,LPCTSTRfieldname)
Argument Description
group Thegrouptowhichthesharedvariablebelongs
fieldname Thenameofthefieldthatcontainsthesharedvariable,inlowercase
ReturnValues
pbfieldID.Returns0xffffiftheIDcannotbefound.
Examples
ThiscodeusesGetSharedVarIDtoobtainthefieldIDofasharedvariable,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);
SeeAlso
Get<type>SharedVarGetSharedVarTypeIsSharedVarArrayIsSharedVarNullIsSharedVarObject
Set<type>SharedVarSetSharedVarToNull
IPB_Sessioninterface:
GetSharedVarTypemethod
Description
Obtainsthedatatypeofthespecifiedsharedvariable.
SyntaxGetSharedVarType(pbgroupgroup,pbfieldIDfid)
Argument Description
group Thegrouptowhichthesharedvariablebelongs
fid TheinternalfieldIDofthesharedvariable
ReturnValues
pbuint.Asimpledatatypedefinedinthelistofpbvalue_typeenumeratedtypes.
Examples
ThisexamplegetsthefieldIDofasharedvariable,thenusesthatIDtogetthetypeofthesharedvariable:pbuintpbvaltype;
curGroup=session->GetCurrGroup();
fid=session->GetSharedVarID(curGroup,"i_svar");
pbvaltype=session->GetSharedVarType(curGroup,fid);
SeeAlso
Get<type>SharedVarGetSharedVarIDIsSharedVarArrayIsSharedVarNullIsSharedVarObjectSet<type>SharedVarSetSharedVarToNull
IPB_Sessioninterface:
GetStringmethod
Description
Returnsapointertothestringpassedinasanargument.
SyntaxGetString(pbstring*string)
Argument Description
string Apointertoapbstring
ReturnValues
LPCTSTR.
Examples
ThisexampleusestheIPB_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.
SeeAlso
GetStringLengthNewStringReleaseStringSetString
IPB_Sessioninterface:
GetStringLengthmethod
Description
Returnsthelengthofastringinbyteswithouttheterminator.
SyntaxGetStringLength(pbstringstring)
Argument Description
string Thepbstringwhoselengthistobedetermined
ReturnValues
pblong.
Examples
Thesestatementssetthevalueofapblongvariabletothelengthofastring:pblonglong_val;
pbstringstr_val;
long_val=session->GetStringLength(str_val);
SeeAlso
GetStringNewStringSetString
IPB_Sessioninterface:
GetSuperClassmethod
Description
Returnstheancestorclassofthespecifiedclass,ifany.
SyntaxGetSuperClass(pbclasscls)
Argument Description
cls Avalidclasshandleforthedescendentclass
ReturnValues
pbclassor0iftheclasshasnoancestor.
Examples
ThesestatementsgettheclassofanobjectinthePBCallInfostructure,theancestorclassofthatclass,andthenthenameoftheancestorclass:pbclasscls,cls_parent;
LPCSTRclsname;
cls=Session->GetClass(ci->pArgs->GetAt(0)->
GetObject());
cls_parent=Session->GetSuperClass(cls);
clsname=Session->GetClassName(cls_parent);
SeeAlso
GetClassGetClassName
IPB_Sessioninterface:
GetSystemClassmethod
Description
Returnsthefirstsystemclassthattheinputclassinheritsfrom.
SyntaxGetSystemClass(pbclasscls)
Argument Description
cls Adescendentclasswhoseancestorsystemclassistobedetermined
ReturnValues
pbclassornullonerror.
SeeAlso
GetMethodIDGetSystemGroup
IPB_Sessioninterface:
GetSystemGroupmethod
Description
ReturnsaPowerBuilderinternalsystemgroup.
SyntaxGetSystemGroup()
ReturnValues
pbclassornullonerror.
Usage
GetSystemGroupreturnsthePowerBuilderinternalsystemgroup,whichcontainsallthesystemtypessuchasPowerObject,NonVisualObject,Structure,Window,CommandButton,andsoon.Youcanusethissystemgrouptoobtainasystemclass.YoumightneedtocallPowerScriptfunctionsinthePowerBuilderextension.Toachievethis,youfirstneedtogetthepbclassthatthePowerScriptfunctionclassresidesin.ThiscodegetsthePowerBuildersystemfunctionclass:pbgroupsysGroup=session->GetSystemGroup();
pbclasssysFuncClass=session->FindClass(sysGroup,
"SystemFunctions");
Afteryougetthesystemclass,youcanobtainthemethodIDofaPowerScriptfunctionbycallingFindMatchingFunction,andthenyoucaninvokethePowerScriptfunction.
SeeAlso
FindMatchingFunctionGetSystemClass
IPB_Sessioninterface:
GetTimeStringmethod
Description
Convertsdatainapbtimeobjecttoastring.
SyntaxGetTimeString(pbtimetime)
Argument Description
time Thepbtimedataobjecttobeconvertedtoastring.
ReturnValues
LPCTSTR.
SeeAlso
NewStringReleaseTimeStringSetString
IPB_Sessioninterface:
HasExceptionThrownmethod
Description
Checksfortheexistenceofanexceptionthathasbeenthrownbutnotcleared.
SyntaxHasExceptionThrown()
ReturnValues
pbboolean.ReturnstrueifaPowerBuilderexceptionhasbeenthrownbutnotcleared.
Examples
Thisexampletestswhetheranexceptionhasbeenthrownsoitcanbehandledandcleared:try
{
session->InvokeObjectFunction(pbobj,mid,&ci);
//WasPBexceptionthrown?
if(session->HasExceptionThrown())
{
//HandlePBexception
session->ClearException();
}
}
SeeAlso
ClearExceptionGetExceptionThrowException
IPB_Sessioninterface:
HasPBVisualObjectmethod
Description
DetermineswhetheranyPowerBuilderwindows,visibleorhidden,arestillinexistence.
SyntaxHasPBVisualObject()
ReturnValues
pbboolean.ReturnstrueifanyPowerBuilderwindowsarestillalive.Ifanywindowsthatarenotresponsewindowsarestillalive,thePowerBuilderapplicationreturnsimmediatelyunlessyoumanuallyaddamessageloop.
Examples
ThisexampleissimilartotheexampleforRestartRequested,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();
}
Usage
RestartRequestedandHasVisualPBObjectareusedintheimplementationoftheIPB_VMRunApplicationfunction.YounolongerneedtouseanexternalmessagelooptocheckforWindowsmessageswhenyoucalltheRunApplicationfunctionasyoudidinversionsofPBNIpriortoPowerBuilder10.5.
SeeAlso
RestartRequestedRunApplication
IPB_Sessioninterface:
InitCallInfomethod
Description
InitializesthePBCallInfostructure.
SyntaxInitCallInfo(pbclasscls,pbmethodIDmid,PBCallInfo*ci)
Argument Description
cls Thepbclasscontainingthemethod
mid ThepbMethodIDreturnedbyGetMethodID
ci ApointertoapreallocatedPBCallInfostructure
ReturnValues
PBXRESULT.ReturnsPBX_OKonsuccess,andPBX_E_INVALID_ARGUMENTonfailure.
Examples
ThisexampleshowstheimplementationofaTriggerEventfunctioninavisualclass.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);
}
Usage
Onreturn,thismethodallocatesenoughspaceforthearguments,and
theninitializestheargumentsandreturnvalue.YoumustsetappropriatevaluesinthePBCallInfostructure.Notethatthestructureitselfmusthavebeenallocatedbeforethecall.
SeeAlso
FreeCallInfo
IPB_Sessioninterface:
InvokeClassFunctionmethod
Description
Invokessystemoruserglobalfunctions.
SyntaxInvokeClassFunction(pbclasscls,pbmethodIDmid,PBCallInfo*ci)
Argument Description
cls
Theclassthatcontainstheglobalfunction.Ifthisisasystemfunction,clsisobtainedwithGetSystemFunctionsClass;otherwise,itisobtainedwithFindGroupandFindClass,withthefunctionnameasthegroup/classname.
mid ThepbMethodIDreturnedbyGetMethodID.
ci ApointertoapreallocatedPBCallInfostructure.
ReturnValues
PBXRESULT.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
Examples
ThisexamplegetsthePowerBuildersystemclassandusesittoinvokethedoublefunction: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);
Usage
Onreturn,thismethodallocatesenoughspacesforthearguments,andtheninitializesargumentsandreturnvalue.YoumustsetappropriatevaluesinthePBCallInfostructure.Notethatthestructureitselfmusthavebeenallocatedbeforethecall.
SeeAlso
InvokeObjectFunction
IPB_Sessioninterface:
InvokeObjectFunctionmethod
Description
Invokesaclassmembermethod.
SyntaxInvokeObjectFunction(pbobjectobj,pbmethodIDmid,PBCallInfo*ci)
Argument Description
obj Thepbobjectcontainingthemethod
mid ThepbMethodIDreturnedbyGetMethodID
ci ApointertoapreallocatedPBCallInfostructure
ReturnValues
PBXRESULT.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
Examples
ThiscodeinvokestheDataWindowUpdatefunctionandreturnsitsintegerreturnvalue: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;
SeeAlso
InvokeClassFunction
IPB_Sessioninterface:
IsArrayItemNullmethod
Description
Returnstrueifthearrayitemcontainsanullvalue;otherwiseitreturnsfalse.
SyntaxIsArrayItemNull(pbarrayarray,pblongdim[])
Argument Description
array Avalidpbarraystructurethatyouwanttocheckforanull-valuedarrayitem.
dimApblongarraytoholdtheindexesofeachdimensionofthearray.Thesizeofthearraymustequalthedimensionsofarray.
ReturnValues
pbboolean.
SeeAlso
GetArrayItemTypeSet<type>ArrayItemSetArrayItemToNull
IPB_Sessioninterface:
IsAutoInstantiatemethod
Description
Returnstrueifthespecifiedclassisanautoinstantiatedclass;otherwiseitreturnsfalse.
SyntaxIsAutoInstantiate(pbclass)
Argument Description
cls Avalidclasshandleorstructure
ReturnValues
pbboolean.
IPB_Sessioninterface:
IsFieldArraymethod
Description
Returnstrueifthefieldofthespecifiedobjectisanarray;otherwiseitreturnsfalse.
SyntaxIsFieldArray(pbclasscls,pbfieldfid)
Argument Description
cls Avalidclasshandlefortheclasswhosefieldistobeaccessed
fid ThefieldIDofthespecifiedobject
ReturnValues
pbboolean.
Examples
Thiscodetestswhetherthefieldidentifiedbyfidisanarray,andifso,getsthearrayvalue:fid=session->GetFieldID(cls,"arr_val");
if(session->IsFieldArray(cls,fid))
{
arr_val=session->GetArrayField(myobj,fid,isNull);...
SeeAlso
GetFieldIDGetFieldTypeGet<type>FieldGetNumOfFieldsIsFieldNullIsFieldObjectSetFieldToNull
Set<type>Field
IPB_Sessioninterface:
IsFieldNullmethod
Description
Returnstrueifthefieldofthespecifiedobjectisanullvalue;otherwiseitreturnsfalse.
SyntaxIsFieldNull(pbobjectobj,pbfieldfid)
Argument Description
obj Avalidobjecthandlefortheobjectwhosefieldistobeaccessed
fid ThefieldIDofthespecifiedobject
ReturnValues
pbboolean.
Examples
Thesestatementstestwhetherthefieldidentifiedbyfidisnull:fid=session->GetFieldID(cls,"i_val");
if(session->IsFieldNull(myobj,fid))
SeeAlso
GetFieldIDGetFieldTypeGet<type>FieldGetNumOfFieldsIsFieldArrayIsFieldObjectSetFieldToNullSet<type>Field
IPB_Sessioninterface:
IsFieldObjectmethod
Description
Returnstrueifthefieldofthespecifiedobjectisanobject;otherwiseitreturnsfalse.
SyntaxIsFieldObject(pbclasscls,pbfieldfid)
Argument Description
cls Avalidclasshandlefortheclasswhosefieldistobeaccessed
fid ThefieldIDofthespecifiedobject
ReturnValues
pbboolean.
Examples
Thesestatementstestwhetherthefieldidentifiedbyfidisanobject:fid=session->GetFieldID(cls,"obj_val");
if(session->IsFieldObject(myobj,fid))
SeeAlso
GetFieldIDGetFieldTypeGet<type>FieldGetNumOfFieldsIsFieldArrayIsFieldNullSetFieldToNullSet<type>Field
IPB_Sessioninterface:
IsGlobalVarArraymethod
Description
Returnstrueiftheglobalvariablecontainsanarray;otherwiseitreturnsfalse.
SyntaxIsGlobalVarArray(pbfieldfid)
Argument Description
fid ThefieldIDoftheglobalvariable
ReturnValues
pbboolean.
Examples
Thesestatementstestwhetherthefieldidentifiedbyfidisaglobalvariablearray:fid=session->GetGlobalVarID("arr_gvar");
if(session->IsGlobalVarArray(fid))
{
arr_val=session->GetArrayGlobalVar(fid,isNull);
...
SeeAlso
GetGlobalVarIDGetGlobalVarTypeGet<type>GlobalVarIsGlobalVarNullIsGlobalVarObjectSetGlobalVarToNullSet<type>GlobalVar
IPB_Sessioninterface:
IsGlobalVarNullmethod
Description
Returnstrueiftheglobalvariablecontainsanullvalue;otherwiseitreturnsfalse.
SyntaxIsGlobalVarNull(pbfieldfid)
Argument Description
fid ThefieldIDoftheglobalvariable
ReturnValues
pbboolean.
Examples
Thesestatementstestwhetherthefieldidentifiedbyfidisaglobalvariablearray:fid=session->GetGlobalVarID("arr_gvar");
if(session->IsGlobalVarArray(fid))
{
arr_val=session->GetArrayGlobalVar(fid,isNull);
...
SeeAlso
GetGlobalVarIDGetGlobalVarTypeGet<type>GlobalVarIsGlobalVarArrayIsGlobalVarObjectSetGlobalVarToNullSet<type>GlobalVar
IPB_Sessioninterface:
IsGlobalVarObjectmethod
Description
Returnstrueiftheglobalvariablecontainsanobject;otherwiseitreturnsfalse.
SyntaxIsGlobalVarObject(pbfieldfid)
Argument Description
fid ThefieldIDoftheglobalvariable
ReturnValues
pbboolean.
Examples
Thesestatementstestwhetherthefieldidentifiedbyfidisaglobalvariableobject.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);
}
SeeAlso
GetGlobalVarIDGetGlobalVarTypeGet<type>GlobalVar
IsGlobalVarArrayIsGlobalVarNullSetGlobalVarToNullSet<type>GlobalVar
IPB_Sessioninterface:
IsNativeObjectmethod
Description
Determineswhetherapbobjectisaninstanceofanativeclass.
SyntaxIsNativeObject(pbobjectobj)
Argument Description
obj Avalidobjecthandle
ReturnValues
pbboolean.
Examples
Thef_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.
SeeAlso
GetNativeInterface
IPB_Sessioninterface:
IsSharedVarArraymethod
Description
Returnstrueifthesharedvariablecontainsanarray;otherwiseitreturnsfalse.
SyntaxIsSharedVarArray(pbgroupgroup,pbfieldfid)
Argument Description
group Thegroupwhosesharedvariableistobeaccessed
fid ThefieldIDofthesharedvariable
ReturnValues
pbboolean.
SeeAlso
Get<type>SharedVarGetSharedVarIDGetSharedVarTypeIsSharedVarNullIsSharedVarObjectSet<type>SharedVarSetSharedVarToNull
IPB_Sessioninterface:
IsSharedVarNullmethod
Description
Returnstrueifthesharedvariablecontainsanullvalue;otherwiseitreturnsfalse.
SyntaxIsSharedVarNull(pbgroupgroup,pbfieldfid)
Argument Description
group Thegroupwhosesharedvariableistobeaccessed
fid ThefieldIDofthesharedvariable
ReturnValues
pbboolean.
SeeAlso
Get<type>SharedVarGetSharedVarIDGetSharedVarTypeIsSharedVarArrayIsSharedVarObjectSet<type>SharedVarSetSharedVarToNull
IPB_Sessioninterface:
IsSharedVarObjectmethod
Description
Returnstrueifthesharedvariablecontainsanobject;otherwiseitreturnsfalse.
SyntaxIsSharedVarObject(pbgroupgroup,pbfieldfid)
Argument Description
group Thegroupwhosesharedvariableistobeaccessed
fid ThefieldIDofthesharedvariable
ReturnValues
pbboolean.
SeeAlso
Get<type>SharedVarGetSharedVarIDGetSharedVarTypeIsSharedVarArrayIsSharedVarNullSet<type>SharedVarSetSharedVarToNull
IPB_Sessioninterface:
NewBlobmethod
Description
Createsanewblobandduplicatesabufferforthenewblobdata.
SyntaxNewBlob(constvoid*bin,pblonglen)
Argument Description
bin Avoidpointerthatpointstothesourcebuffer
len Thelengthinbytesofthedatainthebuffer
ReturnValues
pbblob.
Examples
IftheblobvalueinthePBCallInfostructureisnull,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();
Usage
ThebuffercontainingthenewblobdataisfreedwhenPopLocalFrameiscalled.
SeeAlso
PopLocalFrameSetBlob
IPB_Sessioninterface:
NewBoundedObjectArraymethod
Description
CreatesaboundedPowerBuilderobjectorstructurearray.
SyntaxNewBoundedObjectArray(pbclasscls,pbuintdimension,PBArrayInfo::ArrayBound*
Argument Description
cls AvalidclasshandleofthetypeofPowerBuilderobjectorstructurearraytobecreated
dimension Anumbergreaterthanonethatindicatesthedimensionofthearraytobecreated
bounds Anarraycontainingtheupperandlowerboundariesofthearraytobecreated
ReturnValues
pbarrayornullonfailure.
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);
SeeAlso
Get<type>ArrayItemGetArrayInfoGetArrayItemTypeGetArrayLengthIsArrayItemNullNewBoundedSimpleArrayNewUnboundedObjectArrayNewUnboundedSimpleArrayReleaseArrayInfoSet<type>ArrayItemSetArrayItemToNullSetArrayItemValue
IPB_Sessioninterface:
NewBoundedSimpleArraymethod
Description
Createsaboundedsimpledataarray.
SyntaxNewBoundedSimpleArray(pbuinttype,pbuintdimension,PBArrayInfo::ArrayBound*
Argument Description
type Anenumeratedvariableoftypepbvalue_*indicatingthetypeofsimpleunboundedarraytobecreated
dimension Anumbergreaterthanonethatindicatesthedimensionofthearraytobecreated
bounds Anarraycontainingtheupperandlowerboundariesofthearraytobecreated
ReturnValues
pbarrayornullonfailure.
SeeAlso
Get<type>ArrayItemGetArrayInfoGetArrayItemTypeGetArrayLengthIsArrayItemNullNewBoundedObjectArrayNewUnboundedObjectArrayNewUnboundedSimpleArrayReleaseArrayInfoSet<type>ArrayItem
SetArrayItemToNullSetArrayItemValue
IPB_Sessioninterface:
NewDatemethod
Description
Createsanewpbdatedataobject.
SyntaxNewDate()
ReturnValues
pbdate.
Examples
Thisexampletestswhetheradatevalueexists,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;
}
Usage
Theinitialvalueis1900-1-1.
SeeAlso
SetDateSplitDate
IPB_Sessioninterface:
NewDateTimemethod
Description
Createsanewpbdatetimedataobject.
SyntaxNewDateTime()
ReturnValues
pbdatetime.
Examples
Thisexampletestswhetheradate/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();
}
Usage
Theinitialvalueis1900-1-10:0:0.0.
SeeAlso
SetDateTimeSplitDateTime
IPB_Sessioninterface:
NewDecimalmethod
Description
Allocatesresourcesforanewdecimaldataobject.
SyntaxNewDecimal()
ReturnValues
pbdecornullonfailure.
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();
SeeAlso
GetDecimalStringReleaseDecimalStringSetDecimal
IPB_Sessioninterface:
NewObjectmethod
Description
Createsanewobjectofthespecifiedtype.
SyntaxNewObject(pbclasscls)
Argument Description
cls Thetypeofobjectorstructureinstancetobecreated
ReturnValues
pbobjectofthegivenclassorstructure.
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);
Usage
Thereturnedobject'slifecycleisrestrictedtothecurrentframeunlessAddGlobalRefiscalledontheobject.
SeeAlso
FindClassFindGroup
IPB_Sessioninterface:
NewProxyObjectmethod
Description
Createsaproxyforaremoteobject.TheproxyisusedtoextendthenetworkprotocolinPowerBuilder.
SyntaxNewProxyObject(pbclasscls)
Argument Description
cls Thetypeofobjectorstructureinstancetobecreated
ReturnValues
pbproxyobject.
Examples
Thisexamplecreatesanewproxyobject,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;
SeeAlso
GetMarshalerSetMarshaler
IPB_Sessioninterface:
NewStringmethod
Description
Createsanewstring.
SyntaxNewString(LPCTSTR)
ReturnValues
pbstring.
Examplespbclasscls;
cls=session->GetSystemFunctionsClass();
if(cls==NULL)
{
ret_val=session->NewString("null");
returnret_val;
}
Usage
ThereturnedstringisdestroyedwhenPopLocalFrameiscalled.
SeeAlso
SetString
IPB_Sessioninterface:
NewTimemethod
Description
Createsanewpbtimedataobject.
SyntaxNewTime()
ReturnValues
pbtime.
Examples
Thesestatementssplitatimeintohours,minutes,andseconds,andthenusetheresultingvaluestosetthevalueofanewtimeobject:Session->SplitTime(ci.returnValue->GetTime(),&hh,
&mm,&ss);
ret_val=Session->NewTime();
Session->SetTime(ret_val,hh,mm,ss);
Usage
Theinitialvalueis0:0:0.0.
SeeAlso
SetTimeSplitTime
IPB_Sessioninterface:
NewUnboundedObjectArraymethod
Description
CreatesanunboundedPowerBuilderobjectorstructuredataarray.
SyntaxNewUnboundedObjectArray(pbclasscls)
Argument Description
cls AvalidclasshandleofthetypeofPowerBuilderobjectorstructurearraytobecreated
ReturnValues
pbarrayornullonfailure.
Usage
Anunboundedarraycanhaveonlyonedimension,sonodimensioninformationisneeded.
SeeAlso
Get<type>ArrayItemGetArrayInfoGetArrayItemTypeGetArrayLengthIsArrayItemNullNewBoundedObjectArrayNewBoundedSimpleArrayNewUnboundedSimpleArrayReleaseArrayInfoSet<type>ArrayItemSetArrayItemToNull
SetArrayItemValue
IPB_Sessioninterface:
NewUnboundedSimpleArraymethod
Description
Createsanunboundedsimpledataarray.
SyntaxNewUnboundedSimpleArray(pbuinttype)
Argument Description
type Anenumeratedvariableoftypepbvalue_*indicatingthetypeofsimpleunboundedarraytobecreated
ReturnValues
pbarrayornullonfailure.
Examples
ThisexamplecreatesanunboundedsimpledataarrayofthetypereturnedbythegetDataTypemethod,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);
Usage
Anunboundedarraycanhaveonlyonedimension,sonodimensioninformationisneeded.
SeeAlso
Get<type>ArrayItemGetArrayInfoGetArrayItemTypeGetArrayLengthIsArrayItemNullNewBoundedObjectArrayNewBoundedSimpleArrayNewUnboundedObjectArrayReleaseArrayInfoSet<type>ArrayItemSetArrayItemToNullSetArrayItemValue
IPB_Sessioninterface:
PopLocalFramemethod
Description
Popsthecurrentlocalreferenceframefromthecurrentnativemethodstackframe,removingalllocalreferencestotheobjectsaddedinthatlocalframe.Allthepbobject,pbstring,andpbdecimalvariablescreatedbycallingNewDecimal,NewObject,orNewStringinthecurrentframearedestroyedautomatically.
SyntaxPopLocalFrame()
ReturnValues
None.
SeeAlso
AddLocalRefPushLocalFrameRemoveLocalRef
IPB_Sessioninterface:
ProcessPBMessagemethod
Description
ChecksthePowerBuildermessagequeueand,ifthereisamessageinthequeue,attemptstoprocessit.
SyntaxProcessPBMessage()
ReturnValues
pbboolean.ReturnstrueifaPowerBuildermessagewasprocessed,andfalseotherwise.
Examples
ThismessageloopinaWinMainfunctionprocessesaPowerBuildermessageifamessagehasbeenreceivedandanIPBsessionisrunning: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.Itissimilartothe
PowerBuilderYieldfunction;however,ProcessPBMessageprocessesonlyonemessageatatime,anditprocessesonlyPowerBuildermessages.TheYieldfunctionalsoprocessesWindowsmessages.UsethisfunctionwhenPowerBuilderwindowsorvisualcontrolsarecalledfromC++applicationsorfromextensionstoensurethateventspostedtothePowerBuildermessagequeueareprocessed.IfthefunctionisnotinsertedintheC++applicationinawaythatresultsinitbeingcalledrepeatedly,postedeventsarenotprocessedinthePowerBuilderapplication.Formostapplications,ProcessPBMessagecanbeinsertedinamessageloopintheWinMainfunction.IfyouuseMicrosoftFoundationClasses(MFC),youcannotmodifythebuilt–inmessageloop.ToensurethattheProcessPBMessagefunctioniscalledrepeatedly,youcanoverloadtheCWnd::WindowProcfunctionandinsertProcessPBMessageintotheoverloadedfunction.
IPB_Sessioninterface:
PushLocalFramemethod
Description
Pushesalocalreferenceframeontothecurrentnativemethodstackframe.AlocalframeisanalogoustoascopeinC++.
SyntaxPushLocalFrame()
ReturnValues
None.
SeeAlso
PopLocalFrameRemoveLocalRef
IPB_Sessioninterface:
Releasemethod
Description
ReleasesthecurrentIPB_Session.TheIPB_Sessionobjectbecomesinvalidafterthecall.
SyntaxRelease()
ReturnValues
None.
Examples
ThisexampleshowsacalltoRelease.Theexamplecheckswhetherthereisavalidsessionobjectbeforeattemptingtoreleaseit:if(pIPB_ObjectFactory)
{
pIPB_ObjectFactory->Release();
pIPB_ObjectFactory=NULL;
}
IPB_Sessioninterface:
ReleaseArrayInfomethod
Description
ReleasesmemoryreturnedbyGetArrayInfo.
SyntaxReleaseArrayInfo(PBArrayInfo*pbarrayinfo)
Argument Description
pbarrayinfoAvalidPBArrayInfohandle
ReturnValues
PBXRESULT.PBX_OKforsuccess.
Examples
ThisexampleshowshowReleaseArrayInfoshouldbecalledwhenmemoryallocatedbyGetArrayInfoisnolongerneeded:PBArrayInfo*ai;
...
session->ReleaseArrayInfo(ai);
Usage
Ifthearrayisanunboundedarray,theboundsinformationinPBArrayInfoisundetermined.
SeeAlso
Get<type>ArrayItemGetArrayInfoGetArrayItemTypeGetArrayLengthIsArrayItemNullNewBoundedObjectArrayNewBoundedSimpleArray
NewUnboundedObjectArrayNewUnboundedSimpleArraySet<type>ArrayItemSetArrayItemToNullSetArrayItemValue
IPB_Sessioninterface:
ReleaseDateStringmethod
Description
FreesthememoryacquiredusingGetDateString.
SyntaxReleaseDateString(LPCTSTRstring)
Argument Description
string Thestringtobereleasedfrommemory
ReturnValues
None.
SeeAlso
GetDateString
IPB_Sessioninterface:
ReleaseDateTimeStringmethod
Description
FreesthememoryacquiredusingGetDateTimeString.
SyntaxReleaseDateTimeString(LPCTSTRstring)
Argument Description
string Thestringtobereleasedfrommemory
ReturnValues
None.
SeeAlso
GetDateTimeString
IPB_Sessioninterface:
ReleaseDecimalStringmethod
Description
FreesthememoryacquiredusingGetDecimalString.
SyntaxReleaseDecimalString(LPCTSTRstring)
Argument Description
string Thestringtobereleasedfrommemory
ReturnValues
None.
SeeAlso
GetDecimalString
IPB_Sessioninterface:
ReleaseResultSetAccessormethod
Description
ReleasesthepointerobtainedusingGetResultSetAccessor.
SyntaxReleaseResultSetAccessor(IPB_ResultSetAccessor*rs)
Argument Description
rs ApointertotheIPB_ResultSetAccessorobjecttobereleased
ReturnValues
None.
Examples
ThisstatementreleasestheIPB_ResultSetAccessorobjectrsa:Session->ReleaseResultSetAccessor(rsa);
Usage
WhenyoucallReleaseResultSetAccessor,theReleasefunctionoftheIPB_ResultSetAccessorinterfaceiscalledonthersargumenttoreleasetheinterfacepointer.
SeeAlso
CreateResultSetGetResultSetAccessor
IPB_Sessioninterface:
ReleaseStringmethod
Description
FreesthememoryacquiredusingGetString,GetClassName,GetFieldName,orGetEnumItemName.
SyntaxReleaseString(LPCTSTRstring)
Argument Description
string Thestringtobereleasedfrommemory
ReturnValues
None.
Examples
Thefollowingexamplegetsapointertoeachoftwostringspassedinasarguments,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;
}
Usage
Donotusethisfunctiontoreleaseastringobtainedusing
GetDateString,GetTimeString,GetDateTimeString,orGetDecimalString.EachoftheseGetmethodshasacorrespondingReleasemethod.
SeeAlso
GetClassNameGetEnumItemNameGetFieldNameGetString
IPB_Sessioninterface:
ReleaseTimeStringmethod
Description
FreesthememoryacquiredusingGetTimeString.
SyntaxReleaseTimeString(LPCTSTRstring)
Argument Description
string Thestringtobereleasedfrommemory
ReturnValues
None.
SeeAlso
GetTimeString
IPB_Sessioninterface:
ReleaseValuemethod
Description
FreestheIPB_ValueacquiredusingAcquireValueorAcquireArrayItemValue.
SyntaxReleaseValue(IPB_Value*value)
Argument Description
value Thestringtobereleasedfrommemory
ReturnValues
None.
Examples
TheAcquireValuemethodisusedtoobtainamessageargumentvalue.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);
}
Usage
WhenyounolongerneedthedataacquiredusingtheAcquireValueorAcquireArrayItemValuemethod,youmustcalltheReleaseValuemethodtofreethedata.Failingtodosocausesamemoryleak.DonotuseReleaseValuetoreleaseavaluethatwasnotacquiredusingAcquireValueorAcquireArrayItemValue.Ifyoudo,thePowerBuilder
VMmightcrash.
SeeAlso
AcquireArrayItemValueAcquireValue
IPB_Sessioninterface:
RemoveGlobalRefmethod
Description
RemovesaglobalreferencetothespecifiedPowerBuilderobject.
SyntaxRemoveGlobalRef(pbobjectobj)
Argument Description
obj AvalidPowerBuilderobjecthandle
ReturnValues
None.
ExamplesvoidMyPBNIClass::reference()
{
d_session->AddGlobalRef(d_pbobject);
}
voidMyPBNIClass::unreference()
{
if(d_pbobject!=NULL)
d_session->RemoveGlobalRef(d_pbobject);
}
SeeAlso
AddGlobalRef
IPB_Sessioninterface:
RemoveLocalRefmethod
Description
RemovesalocalreferencetothespecifiedPowerBuilderobject.
SyntaxRemoveLocalRef(pbobjectobj)
Argument Description
obj AvalidPowerBuilderobjecthandle
ReturnValues
None.
SeeAlso
AddLocalRefPopLocalFramePushLocalFrame
IPB_Sessioninterface:
RemovePropmethod
Description
RemovesthespecifiedvariablefromthelistofpropertiesofthecurrentIPBsession.Youmustfreethememorytowhichthepropertypoints.
SyntaxRemoveProp(LPCTSTRname)
Argument Description
name Thenameofthevariabletoberemoved
ReturnValues
None.
Examples
Thesestatementsremoveprop_namefromthelistofvariablesassociatedwiththesessionanddeletethepointercreatedtopointtothevariablesvalue:session->RemoveProp(prop_name);
deleteSetValue;
Usage
SetPropenablesyoutouseavariablevaluethroughoutanIPBsession.UseRemoveProptoremovethevariablefromthelistofvariablesassociatedwiththesessionwhenitisnolongerneeded.Youmustalsofreethememoryassociatedwiththevariable.
SeeAlso
GetPropSetProp
IPB_Sessioninterface:
RestartRequestedmethod
Description
DetermineswhetherthePowerBuildersystemfunctionRestarthasbeencalled.
SyntaxHasPBVisualObject()
ReturnValues
pbboolean.ReturnstruewhenthePowerBuildersystemfunctionRestartiscalled.WhenRestartRequestedreturnstrue,youshoulddestroytheexistingIPB_Sessionobjectandcreateanewonetorestarttheapplication.
Examples
Inthefollowingexample,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();
}
Usage
RestartRequestedandHasVisualPBObjectareusedintheimplementationoftheIPB_VMRunApplicationfunction.YounolongerneedtouseanexternalmessagelooptocheckforWindowsmessageswhenyoucalltheRunApplicationfunctionasyoudidinversionsofPBNIpriortoPowerBuilder10.5.
SeeAlso
HasPBVisualObjectRunApplication
IPB_Sessioninterface:
Set<type>ArrayItemmethod
Description
Assignsavaluetoanarrayitemofaspecifictype.
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.
ReturnValues
PBXRESULT.PBX_OKforsuccess.Iftheindexexceedstheboundsofaboundedarray,itreturnsPBX_E_ARRAY_INDEX_OUTOF_BOUNDS.Ifthedatapassedindoesnotmatchthedatatypeofthearray,itreturnsPBX_E_MISMATCHED_DATA_TYPE.
Examples
Thisexamplecreatesanewunboundedsimplearray.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);
Usage
ThismethodassignstheIPB_ValuepointedtobythevalueargumenttothearrayiteminthesamewaythattheIPB_ValueSet<type>methodsetsavalue.
SeeAlso
Get<type>ArrayItemGetArrayInfo
GetArrayItemTypeGetArrayLengthIsArrayItemNullNewBoundedObjectArrayNewBoundedSimpleArrayNewUnboundedObjectArrayNewUnboundedSimpleArrayReleaseArrayInfoSetArrayItemToNullSetArrayItemValue
IPB_Sessioninterface:
Set<type>Fieldmethod
Description
Asetofmethodsthatsetanewvalueinaninstancefieldofanobject.
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
ReturnValues
PBX_RESULT.
Examples
Thesestatementssetanewstringvalueinastringfield:pbstringstr=session->NewString(d_message.c_str());
if(str!=NULL)
session->SetPBStringField(d_pbobj,d_fidMsg,str);
Usage
WhenyouchangeanyvisualpropertyofaPowerBuilderobjectbycallingSet<type>fieldfunctions,thepropertyischangedbutthepropertyisnotrefreshedinthegraphicaluserinterface.UpdateFieldrefreshesthevisualpropertiesofPowerBuilderobjects.YoumustcallUpdateFieldexplicitlywhenchanginganyvisualpropertywiththeSet<type>fieldfunctions.
SeeAlso
GetFieldIDGetFieldTypeGet<type>FieldGetNumOfFieldsIsFieldArrayIsFieldNullIsFieldObjectSetFieldToNullUpdateField
IPB_Sessioninterface:
Set<type>GlobalVarmethod
Description
Asetofmethodsthatsetthevalueofaglobalvariableofaspecificdatatype.
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
ReturnValues
PBX_RESULT.
Examples
Thisshowshowtoadd1tothevalueofaglobalvariable:fid=session->GetGlobalVarID("l_gvar");
l_val=session->GetLongGlobalVar(fid,isNull);
session->SetLongGlobalVar(fid,l_val+1);
SeeAlso
GetGlobalVarIDGetGlobalVarTypeGet<type>GlobalVarIsGlobalVarObjectSetGlobalVarToNull
IPB_Sessioninterface:
Set<type>SharedVarmethod
Description
Asetofmethodsthatsetthevalueofasharedvariableofaspecificdatatype.
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
ReturnValues
PBX_RESULT.
SeeAlso
Get<type>SharedVarGetSharedVarIDGetSharedVarTypeIsSharedVarArrayIsSharedVarNullIsSharedVarObjectSetSharedVarToNull
IPB_Sessioninterface:
SetArrayItemToNullmethod
Description
Setsthevalueofanarrayitemtoanullvalue.
SyntaxSetArrayItemToNull(pbarrayarray,pblongdim[])
Argument Description
array Avalidpbarraystructureinwhichyouwanttosetanarrayitemtonull.
dimApblongarraytoholdtheindexesofeachdimensionofthearray.Thesizeofthearraymustequalthedimensionsofarray.
ReturnValues
pbboolean.
SeeAlso
IsArrayItemNull
IPB_Sessioninterface:
SetArrayItemValuemethod
Description
SetsthevalueofanarrayitemtothevalueofanIPB_Value.
SyntaxSetArrayItemValue(pbarrayarray,pblongdim[],IPB_Value*src)
Argument Description
array Avalidpbarraystructureinwhichyouwanttosetanarrayitemtonull.
dimApblongarraytoholdtheindexesofeachdimensionofthearray.Thesizeofthearraymustequalthedimensionsofarray.
src Thevaluetowhichthearrayitemistobechanged.
ReturnValues
None.
Examples
Thiscodesetsthevalueofeachiteminanarray:for(i=1;i<=bound;i++)
{
dim[0]=i;
ipv=Session->AcquireArrayItemValue(refArg,dim);
Session->SetArrayItemValue(*i_array,dim,ipv);
Session->ReleaseValue(ipv);
}
Usage
TheSetArrayItemValuemethoddoesnotverifythatthedatatypeofthereplacementvaluematchesthedatatypeoftheoriginalvalue.
SeeAlso
AcquireArrayItemValue
ReleaseValueSetArrayItemToNullSetValue
IPB_Sessioninterface:
SetBlobmethod
Description
Destroystheexistingdatainablobandcopiesdataintoitfromabuffer.
SyntaxSetBlob(pbblobblb,constvoid*bin,pblonglen)
Argument Description
blb Avalidpbblobobjectwhosevalueistobereset
bin Apointertothesourcebuffer
len Thelengthinbytesofthedatainthebuffer
ReturnValues
PBXRESULT.ReturnsPBX_OKforsuccessorPBX_E_INVALID_ARGUMENTifthenewblobvalueisinvalid;otherwise,returnsPBX_E_OUTOF_MEMORY.
Usage
Adeepcopyisperformed.Theexistingvalueisdestroyedfirst,andthenthecontentsofthebinargumentarecopiedintoanewvalue.
SeeAlso
NewBlob
IPB_Sessioninterface:
SetDatemethod
Description
Resetsthevalueofthespecifiedpbdateobject.
SyntaxSetDate(pbdatedate,pbintyear,pbintmonth,pbintday)
Argument Description
date Thepbdateobjecttobereset
year Ayearintherange1000to3000
month Amonthintherange1to12
day Adayintherange1to31
ReturnValues
PBX_RESULT.PBX_OKforsuccessorPBX_E_INVALID_ARGUMENTifthenewdateisinvalid.
Examples
ThisexamplesetsthedatetoMarch12,1938:session->SetDate(date_val,1938,3,12);
Usage
Iftheparametersareinvalid,thedateisresetto1900-1-1.
SeeAlso
NewDateSplitDate
IPB_Sessioninterface:
SetDateTimemethod
Description
Resetsthevalueofthespecifiedpbdatetimeobject.
SyntaxSetDate(pbdatetimedt,pbintyear,pbintmonth,pbintday,pbinthour
Argument Description
dt Thepbdatetimeobjecttobereset
year Ayearintherange1000to3000
month Amonthintherange1to12
day Adayintherange1to31
hour Anhourintherange0to23
minute Aminuteintherange0to59
second Asecondintherange0to59.999999
ReturnValues
PBX_RESULT.PBX_OKforsuccessorPBX_E_INVALID_ARGUMENTifthenewdatetimeisinvalid.
Examples
ThisexamplesetsthedatetimevaluetoAugust19,1982at10:30:45.10:session->SetDate(date_val,1982,8,19,10,30,45.1);
Usage
Iftheparametersareinvalid,thedatetimevalueisresetto1900-1-10:0:0.0.
SeeAlso
NewDateTimeSplitDateTime
IPB_Sessioninterface:
SetDecimalmethod
Description
Setsthevalueofadecimalvariabletodecimaldatainastring.
SyntaxSetDecimal(pbdecdec,LPCTSTRdec_str)
Argument Description
dec Thedecimaldataobjecttobeset
dec_str Thestringcontainingthedatatobeconvertedtoadecimal
ReturnValues
PBXRESULT.PBX_OKforsuccess.
Examples
ThisexampleusestheIPB_SessionSetDecimalmethodtosetthevalueofavariableoftypepbdec,thenusestheIPB_ValueSetDecimalmethodtosetthereturnvalueinthePBCallInfostructure:pbdecpbdecRet=NULL;
LPTSTRlpDecValueToReturn=NULL;
...
pbdecRet=session->NewDecimal();
session->SetDecimal(pbdecRet,
(LPCTSTR)lpDecValueToReturn);
ci->returnValue->SetDecimal(pbdecRet);
Usage
Ifthestringcontainsinvaliddata,thedecimalvalueissetto0.0.
SeeAlso
GetDecimalStringNewDecimalReleaseDecimalString
IPB_Sessioninterface:
SetFieldToNullmethod
Description
Setsthevalueofthespecifiedfieldtonull.
SyntaxSetFieldToNull(pbobjectobj,pbfieldfid)
Argument Description
obj Avalidobjecthandle
fid ThefieldIDofthespecifiedobject
ReturnValues
None.
SeeAlso
GetFieldIDGetFieldTypeGet<type>FieldGetNumOfFieldsIsFieldArrayIsFieldNullIsFieldObjectSet<type>Field
IPB_Sessioninterface:
SetGlobalVarToNullmethod
Description
Setsthevalueofthespecifiedglobalvariabletonull.
SyntaxSetGlobalVarToNull(pbobjectobj,pbfieldfid)
Argument Description
fid ThefieldIDoftheglobalvariable
ReturnValues
None.
SeeAlso
GetGlobalVarIDGetGlobalVarTypeGet<type>GlobalVarIsGlobalVarArrayIsGlobalVarNullIsGlobalVarObjectSet<type>GlobalVar
IPB_Sessioninterface:
SetMarshalermethod
Description
SetsamarshalerthatwillbeusedtoinvokeremotemethodsandconvertPowerBuilderdataformatstotheuser'scommunicationprotocol.
SyntaxSetMarshaler(pbproxyObjectobj,IPBX_Marshaler*marshaler)
Argument Description
obj AnobjectoftypepbproxyObjecttobeusedasaproxyforaremoteobjectthatwascreatedusingNewProxyObject
marshaler AclassinheritedfromIPBX_Marshaler
ReturnValues
None.
Examples
ThisexamplecreatesaJavaMarshalerclassandassociatesitwithaproxyobject://CreateJavaMarshaler
JavaMarshaler*marshaler=newJavaMarshaler(env,
proxy,jobj);
//AssociatetheJavaMarshalerwiththePBproxy
session->SetMarshaler(proxy,marshaler);
ci->pArgs->GetAt(0)->SetObject(proxy);
ci->returnValue->SetLong(kSuccessful);
returnPBX_OK;
Usage
TheSetMarshalerfunctionassociatesanobjectoftypeIPBX_MarshalerwithaPBProxyobject.Itispossibletoassociatemultiplemarshalerobjectswithasingleproxyobject.Itisalsopossibletoassociateone
marshalerobjectwithmultipleproxyobjects.Neitheroftheseisgoodcodingpracticeandshouldbeavoided.BeforecallingSetMarshaler,youcancalltheIPB_SessionGetMarshalerfunctiontoobtainanexistingmarshalerobjectassociatedwithagivenproxyobject,andthendestroytheexistingmarshalerobjectbeforeassociatinganewmarshalerwiththeproxy.Whenaproxyobjectisdestroyed,itcallstheassociatedmarshalerobject'sDestroymethod.Ifmultipleproxyobjectsareassociatedwithasinglemarshalerobject,youneedtoimplementsomeformofreferencecounting.Otherwise,themarshalerobjectisdestroyedwhenthefirstassociatedproxyobjectisdestroyed,andsubsequentcallstothemarshalerobject'sDestroymethod,whenotherassociatedproxyobjectsaredestroyed,willthrowexceptions.Toavoidtheseissues,thereshouldbeaone-to-onerelationshipbetweenmarshalerandproxyobjects.
SeeAlso
GetMarshalerGetMethodID
IPB_Sessioninterface:
SetPropmethod
Description
Addsanewvariabletothelistofpropertiesofthecurrentsessionorchangesthevalueofanexistingvariable.
SyntaxSetProp(LPCTSTRname,void*data)
Argument Description
name Thenameofthepropertytobeset
data Apointertothedatabufferwherethevariable'svalueresides
ReturnValues
None.
Examples
Inthisexample,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);
}
Usage
SetPropenablesyoutouseavariablevaluethroughoutanIPBsessionwithoutusingaglobalvariable,whichissusceptibletonamespaceconflictswithothersessions.SetPropisoneofasetofthreefunctions:
UseSetProptoregisteranewvariablewiththesessionortochangethevalueofanexistingvariable.UseGetProptoaccessthevariable.UseRemoveProptoremovethevariablefromthelistofvariablesassociatedwiththesessionwhenitisnolongerneeded.
ThissetoffunctionsisparticularlyusefulforworkingwithmultiplethreadsofexecutioninEAServer.SupposeyouwanttothrowanexceptionfromwithinaPBNIextensionandtheexceptionitselfisalsodefinedbythePBNIextension.YoucalltheIPB_SessionNewObjectfunctiontocreateaninstanceoftheexception,causingthePBX_CreateNonVisualObjectfunctiontobecalled.Onewaytosetthevalueofthefieldsoftheexceptionbeforethefunctionreturnsinathread–safemanneristocreateanewobjectorstructuretoholdtheexceptioninformationbeforecallingNewObject.YoucancallSetProptostorethestructureortheobjectinthecurrentIPB_Session.WhenPBX_CreateNonVisualObjectiscalled,youcancallGetProptogetthestructureorobjecttoobtaintheexceptioninformation,thencallRemoveProptoremovethedatayoustoredinthecurrentsession.
SeeAlso
GetPropRemoveProp
IPB_Sessioninterface:
SetSharedVarToNullmethod
Description
Setsthevalueofthespecifiedsharedvariabletonull.
SyntaxSetSharedVarToNull(pbgroupgroup,pbfieldfid)
Argument Description
group Thegrouptowhichthesharedvariablebelongs
fid ThefieldIDofthesharedvariable
ReturnValues
None.
Examples
ThisexampleteststheIsSharedVarNullandSetSharedVarToNullfunctions: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);
SeeAlso
Get<type>SharedVarGetSharedVarIDGetSharedVarTypeIsSharedVarArrayIsSharedVarNullIsSharedVarObject
Set<type>SharedVar
IPB_Sessioninterface:
SetStringmethod
Description
Freesanexistingstringandassignsanewstringvaluetoitbyperformingadeepcopy.
SyntaxSetString(pbstringstring,LPCTSTRsrc)
Argument Description
string Avalidpbstringvariablewhosevalueistobereplaced
src Thestringtobeassignedtostring
ReturnValues
PBXRESULT.ReturnsPBX_OKforsuccessorPBX_E_INVALID_ARGUMENTifthenewstringvalueisinvalid;otherwise,returnsPBX_E_OUTOF_MEMORY.
Examples
ThisexampleusestheIPB_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;
Usage
Adeepcopyisperformed.Theexistingvalueisdestroyedfirst,andthenthecontentsofthesrcargumentarecopiedintoanewvalue.
SeeAlso
NewString
IPB_Sessioninterface:
SetTimemethod
Description
Resetsthevalueofthespecifiedpbtimeobject.
SyntaxSetTime(pbtimetime,pbinthour,pbintminute,pbdoublesecond)
Argument Description
time Thepbtimeobjecttobereset
hour Anhourintherange0to23
minute Aminuteintherange0to59
second Asecondintherange0to59.999999
ReturnValues
PBX_RESULT.PBX_OKforsuccessorPBX_E_INVALID_ARGUMENTifthenewtimeisinvalid.
Examples
Thiscodeputsanewtimewiththevalue01: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();
}
Usage
Iftheparametersareinvalid,thetimeisresetto0:0:0.0.
SeeAlso
NewTimeSplitTime
IPB_Sessioninterface:
SetValuemethod
Description
SetsthevalueofoneIPB_ValueobjecttothevalueofanotherIPB_Valueobject.
SyntaxSetValue(IPB_Value*dest,IPB_Value*src)
Argument Description
dest Thevaluetobereplaced
src Thevaluetowhichdestistobechanged
ReturnValues
None.
Examples
ThesestatementssetthereturnvalueinthePBCallInfostructurecitothevalueIPBValue_ret,thenreleasetheIBPValue_retstructure:Session->SetValue(ci->returnValue,IPBValue_ret);
Session->ReleaseValue(IPBValue_ret);
Usage
UnliketheIPB_ValueSet<type>methods,theSetValuemethoddoesnotverifythatthedatatypeofthereplacementvaluematchesthedatatypeoftheoriginalvalue.Theoriginalvalueisfreedandanewvalueisclonedfromthesrcvalue.UsethismethodifyouwanttoswaptwodifferentIPB_Valueobjectsthathavedifferenttypes.
SeeAlso
AcquireValue,ReleaseValue
IPB_Sessioninterface:
SplitDatemethod
Description
Splitsthespecifiedpbdateobjectintoayear,month,andday.
SyntaxSplitDate(pbdatedate,pbint*year,pbint*month,pbint*day)
Argument Description
date Thepbdateobjecttobesplit
year Ayearintherange1000to3000
month Amonthintherange1to12
day Adayintherange1to31
ReturnValues
PBX_RESULT.PBX_OKforsuccess.
Examples
ThisstatementsplitsthedateinthefirstvalueinthePBCallInfostructure:Session->SplitDate(ci->pArgs->GetAt(0)->
GetDate(),&yy,&mm,&dd);
SeeAlso
NewDate,SetDate,SplitDateTime
IPB_Sessioninterface:
SplitDateTimemethod
Description
Splitsthespecifiedpbdatetimeobjectintoayear,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
ReturnValues
PBX_RESULT.PBX_OKforsuccess.
SeeAlso
NewDateTime,SetDateTime,SplitDate,SplitTime
IPB_Sessioninterface:
SplitTimemethod
Description
Splitsthespecifiedtimeobjectintoanhour,minute,andsecond.
SyntaxSplitTime(pbtimetime,pbint*hour,pbint*minute,pbdouble*second)
Argument Description
time Thepbtimeobjecttobesplit
hour Anhourintherange0to23
minute Aminuteintherange0to59
second Asecondintherange0to59.999999
ReturnValues
PBX_RESULT.PBX_OKforsuccess.
Examples
Thesestatementssplitatimeintohours,minutes,andseconds,andthenusetheresultingvaluestosetthevalueofanewtimeobject:Session->SplitTime(ci.returnValue->GetTime(),&hh,
&mm,&ss);
ret_val=Session->NewTime();
Session->SetTime(ret_val,hh,mm,ss);
SeeAlso
NewTimeSetTime
IPB_Sessioninterface:
ThrowExceptionmethod
Description
ThrowsaPowerBuilderexceptionorinheritedexception,andreplacestheexistingexceptionifthereisone.
SyntaxThrowException(pbobjectex)
Argument Description
ex Theexceptiontobethrown.TheexceptionmustfirstbecreatedwithNewObject.
ReturnValues
None.
Examples
Thiscodecreatesanewexceptionobjectintheclassuser_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;
SeeAlso
ClearExceptionGetExceptionHasExceptionThrown
IPB_Sessioninterface:
TriggerEventmethod
Description
TriggersaPowerBuilderevent.
SyntaxTriggerEvent(pbobjectobj,pbmethodIDmid,PBCallInfo*ci)
Argument Description
obj Thepbobjectcontainingthemethod
mid ThepbMethodIDreturnedbyGetMethodID
ci ApointertoapreallocatedPBCallInfostructure
ReturnValues
PBXRESULT.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
Examples
ThiscodetriggerstheclickedeventonaDataWindowobject:cls=session->GetClass(dwobj);
mid=session->GetMethodID
(cls,"clicked",PBRT_EVENT,"LIILCdwobject.");
session->InitCallInfo(cls,mid,ci);
session->TriggerEvent(dwobj,mid,ci);
...
SeeAlso
GetClassGetMethodID
IPB_Sessioninterface:
UpdateFieldmethod
Description
RefreshesavisualpropertyofaPowerBuilderobject.
SyntaxUpdateField(pbobjectobj,pbfieldIDfid)
Argument Description
obj Thepbobjectwhoseuserinterfacepropertyneedstobechanged
fid ThefieldIDoftheobject
ReturnValues
PBXRESULT.Returnssuccessorfailure.
Examples
ThisfunctionchangesthetitleofaDataWindowcontrol: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;
}
Usage
WhenyouchangeanyvisualpropertyofaPowerBuilderobjectbycallingSet<type>fieldfunctions,thepropertyischangedbutthepropertyisnotrefreshedinthegraphicaluserinterface.UpdateFieldrefreshesthevisualpropertiesofPowerBuilderobjects.Youmustcallthisfunction
explicitlywhenchanginganyvisualpropertywiththeSet<type>fieldfunctions.
SeeAlso
Set<type>Field
IPB_Valueinterface
Description
TheIPB_ArgumentsandIPB_ValueinterfacespassvaluesbetweenthePowerBuilderVMandPowerBuilderextensionmodules.ThroughtheIPB_Valueinterface,youcanaccessinformationabouteachvariable,includingitstype,nullflag,accessprivileges,arrayorsimpletype,andreferencetype.
Methods
Table7-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_Valueinterface:
Get<type>method
Description
Asetofdatatype-specificmethodsthatreturnapointertothedatainIPB_Value.
SyntaxGetArray()
GetBlob()
GetBool()
GetByte()
GetChar()
GetDate()
GetDateTime()
GetDecimal()
GetDouble()
GetInt()
GetLong()
GetLongLong()
GetObject()
GetReal()
GetString()
GetTime()
GetUint()
GetUlong()
ReturnValues
ApredefinedPBNIdatatypethatcorrespondstothePowerBuilderdatatypeinthemethodname.
Examples
ThisstatementgetsthedateinthefirstvalueinthePBCallInfostructureandsplitsitintoyear,month,andday:Session->SplitDate(ci->pArgs->GetAt(0)->
GetDate(),&yy,&mm,&dd);
Usage
IfIPB_Valuecontainsanullvalue,orifyouaretryingtogetaspecificdatatypefromanIPB_Valueinstanceofanotherdatatype,thedataretrievedisundetermined.Ifthedatatypeisstring,blob,decimal,time,date,datetime,array,orobject,thereturnvaluepointstothesameaddresspointedtobyIPB_Value.Asaresult,changingeitherthevariablethatholdsthereturnvalueorthevalueoftheIPB_Valueinstanceaffectstheother.
SeeAlso
Set<type>
IPB_Valueinterface:
GetClassmethod
Description
ReturnstheclasshandleofaPowerBuilderobject.
SyntaxGetClass()
ReturnValues
pbclassornullonerror.
Examplespbclassclz=ci->pArgs->GetAt(i)->GetClass();
SeeAlso
Get<type>GetTypeSet<type>
IPB_Valueinterface:
GetTypemethod
Description
Returnsthedatatypeofasingledataitemorarray.
SyntaxGetType()
ReturnValues
pbuint
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;
...
Usage
IftheIPB_Valueinstancecontainsanobjectorstructure,GetTypereturnstheclassIDofthedata.Otherwise,itreturnsasimpledatatypedefinedinthelistofpbvalue_typeenumeratedtypes.
SeeAlso
Get<type>GetClassSet<type>
IPB_Valueinterface:
IsArraymethod
Description
ReturnstrueiftheIPB_Valueinstancecontainsanarray;otherwise,returnsfalse.
SyntaxIsArray()
ReturnValues
pbboolean
Examples
ThisexampletestswhetheranIPB_Valueinstanceisanarraybeforeobtainingthearray:if(ci->pArgs->GetAt(i)->IsArray())
{
pArguments[i].array_val=
ci->pArgs->GetAt(i)->GetArray();
continue;
}
SeeAlso
IsByRefIsEnumIsObject
IPB_Valueinterface:
IsByRefmethod
Description
ReturnstrueiftheIPB_Valueinstancecontainsabyreferenceargument;otherwiseitreturnsfalse.
SyntaxIsByRef()
ReturnValues
pbboolean
Examples
ThisexampleshowshowyouwoulduseIsByReftotestwhetheranargumentisobtainedbyreference:if(ci->pArgs->GetAt(i)->IsByRef())
...
SeeAlso
IsArrayIsEnumIsObject
IPB_Valueinterface:
IsEnummethod
Description
ReturnstrueiftheIPB_Valueinstancecontainsanenumeratedvalue;otherwiseitreturnsfalse.
SyntaxIsEnum()
ReturnValues
pbboolean
SeeAlso
GetEnumItemNameGetEnumItemValue
IPB_Valueinterface:
IsNullmethod
Description
ReturnstrueiftheIPB_Valueinstancecontainsanullvalue;otherwise,itreturnsfalse.
SyntaxIsNull()
ReturnValues
pbboolean
Examples
ThisexampletestswhetheranIPB_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;
}
...
SeeAlso
IsArrayIsByRefIsObjectSetToNull
IPB_Valueinterface:
IsObjectmethod
Description
ReturnstrueiftheIPB_Valueinstancecontainsanobjectorobjectarray;otherwiseitreturnsfalse.
SyntaxIsObject()
ReturnValues
pbboolean
Examples
ThisexampletestswhetheranIPB_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;
}
...
SeeAlso
IsArrayIsByRefIsEnum
IPB_Valueinterface:
Set<type>method
Description
Setofdatatype-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)
ReturnValues
PBXRESULT.
Examples
ThisexampleusestheIPB_ValueSetPBStringmethodtosetvaluesinPBCallInfo.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;
Usage
ThesemethodsautomaticallysetthevalueofIPB_Valuetonotnullandreturnanerrorifthedatatypetobesetdoesnotmatchtheexistingdatatype.TheerrorcodeisPBX_E_MISMATCHED_DATA_TYPE.Ifthevalueisaread-onlyargument,itreturnstheerrorPBX_E_READONLY_ARGS.Ifthedatatypeisstringorblob,adeepcopyisperformed.Theexistingvalueisdestroyedfirst,andthenthecontentsoftheargumentarecopiedintoanewvalue.
SeeAlso
Get<type>
IPB_Valueinterface:
SetToNullmethod
Description
SetsthedatacontainedintheIPB_Valueinstancetonullsothedatacanbereset.
SyntaxSetToNull()
ReturnValues
PBXRESULT.Ifthevalueisaread-onlyargument,theerrorPBX_E_READONLY_ARGSisreturned.
Examples
ThisexampleshowstheuseofSetToNullwhenanullblobvalueisreturned: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;
...
SeeAlso
IsEnum
IPB_VMinterface
Description
TheIPB_VMinterfaceloadsPowerBuilderapplicationsinthird-partyapplicationsandinteroperateswiththePowerBuildervirtualmachine(PBVM).
Methods
IPB_VMhastwomethods:CreateSessionRunApplication
IPB_VMinterface:
CreateSessionmethod
Description
CreatesanIPB_SessionobjectthatcanbeusedtocallPowerBuilderfunctions.
SyntaxCreateSession(LPCTSTRapplicationName,LPCTSTR*libraryList,pbuint
Argument Description
applicationNameThenameofthecurrentapplicationobjectinlowercase
libraryList ThelibrarylistofthePowerBuilderapplicationthatcontainstheobjectsandfunctionstobecalled
numLibs Thenumberoflibrariesinthelibrarylist
session ApointertoIPB_Session*,whichwillreturnthecurrentIPB_Sessionpointerafterthecall
ReturnValues
PBXRESULT.PBX_OKforsuccess.
Examples
ThisexamplecreatesanIPB_Sessionwiththesimplelibrarylistmydemo.pbl:IPB_Session*session;
IPB_VM*vm=NULL;
fstreamout;
ifstreamin;
PBXRESULTret;
HINSTANCEhinst=LoadLibrary("pbvm170.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;
SeeAlso
RunApplication
IPB_VMinterface:
RunApplicationmethod
Description
Runsthespecifiedapplication.
SyntaxRunApplication(LPCTSTRapplicationName,LPCTSTR*libraryList,pbuint
Argument Description
applicationNameThenameoftheapplicationobjecttoberun,inlowercase
libraryList Thelibrarylistoftheapplication
numLibs Thenumberoflibrariesinthelibrarylist
commandLine Parameterstobepassedtotheapplicationobject
session ApointertoIPB_Session*,whichwillreturnthecurrentIPB_Sessionpointerafterthecall
ReturnValues
PBXRESULT.PBX_OKforsuccess.
Examples
ThiscodefragmentloadsthePowerBuilderVMandrunsanapplicationcalledrunappthatusesonelibrary,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("pbvm170.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;
}
SeeAlso
CreateSession
IPBX_Marshalerinterface
Description
TheIPBX_MarshalerinterfaceisusedtoinvokeremotemethodsandconvertPowerBuilderdataformatstotheuser'scommunicationprotocol.AmarshalerextensionisaPowerBuilderextensionthatactsasthebridgebetweenPowerBuilderandothercomponents,suchasEJBs,Javaclasses,CORBAobjects,Webservices,andsoon.
Methods
Table7-5:IPBX_Marshalermethods
Method Description
Destroy DestroysaninstanceofanobjectinheritedfromtheIPBX_Marshalerstructure
GetModuleHandle ReturnsthehandleofthePBXthatcontainsthenativeclass
InvokeRemoteMethodUsedinPowerBuildermarshalernativeclassestocallremotemethods
IPBX_Marshalerinterface:
Destroymethod
Description
UsetheDestroymethodtodestroyinstancesofobjectsinheritedfromtheIPBX_Marshalerstructure.
SyntaxDestroy()
ReturnValues
None.
Examples
ThiscodedestroysthecurrentinstanceoftheSampleMarshalerstructure:voidSampleMarshaler::Destroy()
{
deletethis;
}
Usage
Youmustimplementthismethodinthemarshalernativeclassaftercreatinganinstanceofamarshalerstructureandinvokingremotemethods.
SeeAlso
GetModuleHandleInvokeRemoteMethod
IPBX_Marshalerinterface:
GetModuleHandlemethod
Description
ReturnsthehandleofthePBXthatcontainsthenativeclass.ThismethodisrequiredtoallowthePowerBuilderVMtodeterminewhichPBXscanbeunloaded.
SyntaxGetModuleHandle()
ReturnValues
pbulong
Examples
ThiscodeintheimplementationofamarshalerclassreturnsthehandleofthePBX: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;
}
Usage
Youmustimplementthismethodinthemarshalernativeclass.
SeeAlso
DestroyInvokeRemoteMethod
IPBX_Marshalerinterface:
InvokeRemoteMethodmethod
Description
UsedinPowerBuildermarshalernativeclassestocallremotemethods.
SyntaxInvokeRemoteMethod(IPB_Session*session,pbproxyobjectobj,LPCTSTR
Argument Description
session ThisIPBsession
obj Theproxyobjectfortheremoteobject
methodDescAnarbitrarystringstoredasanaliasnamefortheremotemethodintheproxy,forexample:functionintfoo(inta)alias"ThisisamethodinremoteBizTalk"
ci Theparametersandreturnvaluesettingforthecall
ReturnValues
PBXRESULT.PBX_OKifthecallsucceeded.
Examples
Thisexampleshowsaheaderfileforasamplemarshalerclass:#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
}
Usage
Youmustimplementthismethodinthemarshalernativeclass.
SeeAlso
DestroyGetModuleHandle
IPBX_NonVisualObjectinterface
Description
TheIPBX_NonVisualObjectinterfaceinheritsfromIPBX_UserObjectandisthedirectancestorclassofnonvisualPowerBuildernativeclasses.
Methods
IPBX_NonVisualObjectinheritstwomethodsfromtheIPBX_UserObjectinterface:DestroyandInvoke.
IPBX_UserObjectinterface
Description
TheIPBX_UserObjectinterfaceistheancestorclassofthePowerBuildernativeclasses.
Methods
IPBX_UserObjecthastwomethods:DestroyandInvoke
IPBX_UserObjectinterface:
Destroymethod
Description
DestroysthecurrentinstanceofaPowerBuildernativeclassthatinheritsfromIPBX_UserObject.
SyntaxDestroy()
ReturnValues
None.
Examples
ThisexampleshowshowyouwouldcallDestroyfortheclassMyPBNIClass:voidMyPBNIClass::Destroy()
{
deletethis;
}
Usage
Youmustimplementthismethodinthenativeclassaftercreatinganinstanceoftheclassandinvokingremotemethods.
SeeAlso
Invoke
IPBX_UserObjectinterface:
Invokemethod
Description
CallsmethodsinPowerBuildernativeclasses.
SyntaxInvoke(IPB_Session*session,pbobjectobj,pbmethodIDmid,PBCallInfo*
Argument Description
session ThisIPBsession
obj ThePowerBuilderextensionobjecttobeinvoked
mid ThepbMethodIDreturnedbyGetMethodID
ci Theparametersandreturnvaluesettingforthecall
ReturnValues
PBXRESULT.PBX_OKforsuccess.
Examples
Inthisexample,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;
}
SeeAlso
GetMethodID
IPBX_VisualObjectinterface
Description
TheIPBX_VisualObjectinterfaceinheritsfromIPBX_UserObjectandisthedirectancestorclassofvisualPowerBuildernativeclasses.
Methods
IPBX_VisualObjecthasthreedirectmethods:CreateControlGetEventIDGetWindowClassName.
IPBX_NonVisualObjectinheritstwomethodsfromtheIPBX_UserObjectinterface:
DestroyInvoke
IPBX_VisualObjectinterface:
CreateControlmethod
Description
CreatesawindowcontrolandreturnsitshandletothePowerBuilderVM.
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
ReturnValues
HWND.
Examples
Thisispartofavisualextensionexample: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;
}
Usage
ThewindowmustberegisteredbeforeyoucallCreateControl.
SeeAlso
GetEventIDGetWindowClassName
IPBX_VisualObjectinterface:
GetEventIDmethod
Description
Returnstheidentifierofaneventwhenthewindow'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.
ReturnValues
Integer.
Examples
Inthisexample,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;
}
Usage
ThisfunctionisusedtoprocessWindowsmessages,suchasWM_COMMANDandWM_NOTIFY,thataresenttotheparentofanobjectandnottotheobjectitself.Suchmessagescannotbecaughtinthevisualextension'swindowprocedure.ThePBVMcallsGetEventIDtoprocessthesemessages.IfthemessageismappedtoaPowerBuilderevent,GetEventIDreturnstheevent'sidentifier,forexamplePB_BNCLICKED,andtheeventisfiredautomatically.PowerBuildereventtokenidentifiersaremappedtounsignedintegervaluesinthepbevtid.hheaderfile.Theidentifiersinpbevtid.hareassociatedwithPowerBuildereventtokennames.Forexample,theidentifierPB_BNCLICKEDisassociatedwiththetokennamepbm_bnclicked.Ifthemessageisnotmappedtoanevent,GetEventIDreturnsthevaluePB_NULLandthemessageisdiscarded.
SeeAlso
CreateControlGetWindowClassName
IPBX_VisualObjectinterface:
GetWindowClassNamemethod
Description
Returnsthenameofthewindow.
SyntaxGetWindowClassName()
ReturnValues
LPCTSTR.
Examples
ThestringreturnedbyGetWindowClassNameispassedasanargumenttotheCreateControlmethod:LPCTSTRCVisualExt::GetWindowClassName()
{
returns_className;
}
Usage
ThewindowmustberegisteredbeforeyoucallGetWindowClassName.
SeeAlso
CreateControlGetEventID
PBArrayInfostructure
Description
PBArrayInfoisaC++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
Description
PBCallInfoisaC++structureusedtoholdargumentsandreturntypeinformationinfunctioncallsbetweenPBNIandPowerBuilder.
Table7-7:PBCallInfomembers
Member Type Description
pArgs IPB_Arguments* Interfaceusedtoaccessarguments
returnValue IPB_Value Holdsreturndataafterthecall
returnClass pbclass Holdsreturnclassafterthecall
PB_DateDatastructure
Description
ThePB_DateDatastructureisusedtopassdataoftypeDateintheSetDatafunctionintheIPB_RSItemDatainterface.
Table7-8:PB_DateDatamembers
Field Description
year Ashortidentifyingtheyear
monthAshortidentifyingthemonth
day Ashortidentifyingtheday
filler Ashortusedforstructurealignmentonly
SeeAlso
SetData
PB_DateTimeDatastructure
Description
ThePB_DateTimeDatastructureisusedtopassdataoftypeDateTimeintheSetDatafunctionintheIPB_RSItemDatainterface.
Table7-9:PB_DateTimeDatamembers
Field Description
date APB_DateDatastructureidentifyingthedate
time APB_TimeDatastructureidentifyingthetime
SeeAlso
SetData
PB_TimeDatastructure
Description
ThePB_TimeDatastructureisusedtopassdataoftypeTimeintheSetDatafunctionintheIPB_RSItemDatainterface.
Table7-10:PB_DateDatamembers
Field Description
hour Ashortidentifyingthehour
minute Ashortidentifyingtheminute
secondAshortidentifyingthesecond
filler Ashortusedforstructurealignmentonly
SeeAlso
SetData
PBX_DrawItemStructstructure
Description
ThePBX_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–shadowbox2–box
5–lowered6–raised
backColorBackgroundcolorofthevisualcontrol.YoucanobtaintheRGBvalueofthebackgroundcolorusingtheWindowsAPIfunctionsGetRValue,GetGValue,andGetBValue.
SeeAlso
PBX_DrawVisualObject
PBArrayAccessortemplateclass
Description
TherearetwoversionsofthePBArrayAccessortemplateclass.Thefirstversionisusedtoaccesstheitemsinanarrayofastandardtype.Thesecondversionisusedtoaccessitemsinastringarray.ThestandardtypesaredefinedasValueTypesinpbtraits.handarepbint,pbuint,pbbyte,pblong,pblonglong,pbulong,pbboolean,pbreal,pbdouble,pbdec,pbdate,pbtime,pbdatetime,pbchar,pbblob,andpbstring.PBArrayAccessorhasfourmethods:
GetAtIsNullSetAtSetToNull
PBArrayAccessortemplateclass:
GetAtmethod
Description
Obtainsthearrayitematthespecifieddimension.
SyntaxGetAt(pblongdim[])
ReturnValues
ValueType(definedinpbtraits.h).
Argument Description
dim Thedimensionofthearrayitemtobeobtained
Examples
SeeSetAt.
SeeAlso
SetAt
PBArrayAccessortemplateclass:
IsNullmethod
Description
Returnstrueifthearrayitemcontainsanullvalue,otherwisereturnsfalse.
SyntaxIsNull(pblongdim[])
Argument Description
dim Thedimensionofthearrayitemtobetested
ReturnValues
pbboolean.
SeeAlso
GetAt,SetAt,SetToNull
PBArrayAccessortemplateclass:
SetAtmethod
Description
Setsthearrayitematthespecifieddimension.
Syntax
ForarraysofaspecifiedValueType:SetAt(pblongdim[],ValueTypev)
Forstringarrays:SetAt(pblongdim[],LPCTSTRstring)
SetAt(pblongdim[],pbstringstring)
Argument Description
dim Thedimensionofthearrayitemtobeset
v AValueTypedefinedinpbtraits.h
string AstringoftypepbstringorLPCTSTR
ReturnValues
None.
Examples
ThisexampleshowstheuseofGetAtandSetAtinarraysofatypespecifiedbyaValueType: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;
}
SeeAlso
GetAt
PBArrayAccessortemplateclass:
SetToNullmethod
Description
Setsthevalueofthespecifiedarrayitemtonull.
SyntaxSetToNull(pblongdim[])
Argument Description
dim Thedimensionofthearrayitemtobeset
ReturnValues
None.
SeeAlso
GetAtIsNullSetAt
PBBoundedArrayCreatortemplateclass
Description
TherearetwoversionsofthePBBoundedArrayCreatortemplateclass.Thefirstversionisusedtocreateaboundedarrayofastandardtype.ThestandardtypesaredefinedasValueTypesinpbtraits.handarepbint,pbuint,pbbyte,pblong,pblonglong,pbulong,pbboolean,pbreal,pbdouble,pbdec,pbdate,pbtime,pbdatetime,pbchar,pbblob,andpbstring.Thesecondversionisusedtocreateaboundedarrayofstrings.
Methods
PBBoundedArrayCreatorhastwomethods:GetArraySetAt
PBBoundedArrayCreatortemplateclass:
GetArraymethod
Description
Obtainsanarraythathasbeencreated.
SyntaxGetArray()
ReturnValues
pbarray.
Examples
Thisexamplesetsupanarray,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();
}
SeeAlso
SetAt
PBBoundedArrayCreatortemplateclass:
SetAtmethod
Description
Setsavalueorstringtothearrayitematthespecifieddimension.
Syntax
ForarraysofaspecifiedValueType:SetAt(pblongdim[],ValueTypev)
Forstringarrays:SetAt(pblongdim[],LPCTSTRstring)
SetAt(pblongdim[],pbstringstring)
Argument Description
dim Thedimensionofthearrayitemtobeset
v AValueTypedefinedinpbtraits.h
string AstringoftypepbstringorLPCTSTR
ReturnValues
None.
Examples
ThisexampleshowstheuseofSetAtinarraysofatypespecifiedbyaValueType://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);
}
}
}
SeeAlso
GetArray
PBBoundedObjectArrayCreatorclass
Description
ThePBBoundedObjectArrayCreatorclassisusedtocreateanobjectarray.
Methods
PBBoundedObjectArrayCreatorhastwomethods:GetArraySetAt
PBBoundedObjectArrayCreatorclass:
GetArraymethod
Description
Obtainsanarraythathasbeencreated.
SyntaxGetArray()
ReturnValues
pbarray.
Examples
ThisexamplesetsthevaluesinanarrayandthenusesGetArraytoobtainthearray:PBBoundedObjectArrayCreator<pbvalue_string>
ac(session);
for(i=0;i<itemcount1;i++)
{
ac.SetAt(i+1,iarg[i]);
}
out_array=ac.GetArray();
SeeAlso
SetAt
PBBoundedObjectArrayCreatorclass:
SetAtmethod
Description
Setsthearrayitematthespecifieddimension.
Syntax
ForarraysofaspecifiedValueType:SetAt(pblongdim[],ValueTypev)
Forstringarrays:SetAt(pblongdim[],LPCTSTRstring)
SetAt(pblongdim[],pbstringstring)
Argument Description
dim Thedimensionofthearrayitemtobeset
v AValueTypedefinedinpbtraits.h
string AstringoftypepbstringorLPCTSTR
ReturnValues
None.
Examples
ThismethodisincludedintheexampleforGetArray.
SeeAlso
GetArray
PBObjectArrayAccessorclass
Description
ThePBObjectArrayAccessorclassisusedtoaccesstheitemsinanobjectarray.
Methods
PBObjectArrayAccessorhastwomethods:GetAtSetAt
PBObjectArrayAccessorclass:
GetAtmethod
Description
Obtainsthearrayitematthespecifieddimension.
SyntaxGetAt(pblongdim[])
ReturnValues
pbobject.
Argument Description
dim Thedimensionofthearrayitemtobeset
Examples
ThisexampleshowstheuseofGetAtinanobjectarray: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);
}
SeeAlso
SetAt
PBObjectArrayAccessorclass:
SetAtmethod
Description
Setsthearrayitematthespecifieddimension.
SyntaxSetAt(pblongdim[],pbobjectobj)
Argument Description
dim Thedimensionofthearrayitemtobeset
obj Avalidobjecthandle
ReturnValues
None.
Examples
ThisexampleshowstheuseofSetAtinanobjectarray: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);
}
SeeAlso
GetAt
PBUnboundedArrayCreatortemplateclass
Description
TherearetwoversionsofthePBUnboundedArrayCreatortemplateclass.Thefirstversionisusedtocreateanunboundedarrayofastandardtype.ThestandardtypesaredefinedasValueTypesinpbtraits.handarepbint,pbbyte,pbuint,pblong,pblonglong,pbulong,pbboolean,pbreal,pbdouble,pbdec,pbdate,pbtime,pbdatetime,pbchar,pbblob,andpbstring.Thesecondversionisusedtocreateanunboundedarrayofstrings.
Methods
PBUnboundedObjectArrayCreatorhastwomethods:GetArraySetAt
PBUnboundedArrayCreatortemplateclass:
GetArraymethod
Description
Obtainsanarraythathasbeencreated.
SyntaxGetArray()
ReturnValues
pbarray.
Examples
ThisexamplesetsthevaluesinanarrayandthenusesGetArraytoobtainthearray:PBUnboundedArrayCreator<pbvalue_string>ac(session);
for(i=0;i<itemcount1;i++)
{
ac.SetAt(i+1,iarg[i]);
}
out_array=ac.GetArray();
SeeAlso
SetAt
PBUnboundedArrayCreatortemplateclass:
SetAtmethod
Description
Setsthearrayitematthespecifiedposition.
Syntax
ForarraysofaspecifiedValueType:SetAt(pblongpos,ValueTypev)
Forstringarrays:SetAt(pblongpos,LPCTSTRstring)
SetAt(pblongpos,pbstringstring)
Argument Description
pos Apblongidentifyingapositioninthearray
v AValueTypedefinedinpbtraits.h
string AstringoftypepbstringorLPCTSTR
ReturnValues
None.
Examples
ThisexampleshowstheuseofSetAtinarraysofatypespecifiedbyaValueType:PBUnboundedArrayCreator<I>ac(session);
in>>iarg[i];
for(i=0;i<itemcount1;i++)
{
ac.SetAt(i+1,iarg[i]);
}
out_array=ac.GetArray();
SeeAlso
GetArray
PBUnboundedObjectArrayCreatorclass
Description
ThePBUnboundedObjectArrayCreatorclassisusedtocreateanobjectarray.
Methods
PBUnboundedObjectArrayCreatorhastwomethods:GetArraySetAt
PBUnboundedObjectArrayCreatorclass:
GetArraymethod
Description
Obtainsanarraythathasbeencreated.
SyntaxGetArray()
ReturnValues
pbarray.
SeeAlso
SetAt
PBUnboundedObjectArrayCreatorclass:
SetAtmethod
Description
Setsthearrayitematthespecifieddimension.
Syntax
ForarraysofaspecifiedValueType:SetAt(pblongpos,ValueTypev)
Forstringarrays:SetAt(pblongpos,LPCTSTRstring)
SetAt(pblongpos,pbstringstring)
Argument Description
pos Apblongidentifyingapositioninthearray
v AValueTypedefinedinpbtraits.h
string AstringoftypepbstringorLPCTSTR
ReturnValues
None.
SeeAlso
GetArray
Exportedmethods
Description
ThefollowingtablelistsmethodsthatmustbeimplementedinthePowerBuilderextensionmodulewhentheconditionsshowninthetableapply.Themethodsaredescribedafterthetable.ThePBX_GetVersionmethodisusedbyPowerBuildertodeterminewhetherthecompilermacroUNICODEor_UNICODEhasbeenset.Itisforinternaluseonly.
Methods
Table7-12:Methodsthatmustbeexportedbyallextensions
Method Required
PBX_CreateNonVisualObjectWhentheextensioncontainsnonvisualnativeclasses
PBX_CreateVisualObject Whentheextensioncontainsvisualnativeclasses
PBX_DrawVisualObjectWhenyouwanttobeabletodrawavisualrepresentationofthevisualobjectinthePowerBuilderdevelopmentenvironment
PBX_GetDescription Inallextensions
PBX_InvokeGlobalFunction Whentheextensioncontainsglobalfunctions
PBX_Notify Whenyouneedtoinitializeanduninitializeasession
Exportedmethods:
PBX_CreateNonVisualObjectmethod
Description
CreatesanewinstanceofanonvisualPowerBuilderextensionobject.
SyntaxPBX_CreateNonVisualObject(IPB_Session*pbsession,pbobjectpbobj,LPCTSTR
Argument Description
pbsession ThisIPBsession
pbobj ThenameofapbobjectcorrespondingtothePowerBuilderextensionobjecttobecreated
xtraname ThenameofthePowerBuildernativeclassinlowercase
obj ThePowerBuilderextensionobjecttobecreated
ReturnValues
PBXRESULT.PBX_OKforsuccess.
Examples
Inthisexample,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;
};
Usage
YoumustimplementthismethodineveryPowerBuilderextensionmodulethatcontainsnonvisualclasses.WhenyouusetheCREATEstatementinPowerScripttocreateanewPowerBuilderextensionobject,thePBVMcallsthismethod.
SeeAlso
PBX_GetDescription
Exportedmethods:
PBX_CreateVisualObjectmethod
Description
CreatesanewinstanceofavisualPowerBuilderextensionobject.
SyntaxPBX_CreateVisualObject(IPB_Session*pbsession,pbobjectpbobj,LPCTSTR
Argument Description
pbsession ThisIPBsession
pbobj ThenameofapbobjectcorrespondingtothePowerBuilderextensionobjecttobecreated
xtraname ThenameofthePowerBuildernativeclassinlowercase
obj ThePowerBuilderextensionobjecttobecreated
ReturnValues
PBXRESULT.PBX_OKforsuccess.
Examples
Inthisexampletheextensioncontainsseveralclasses.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;
};
Usage
YoumustimplementthismethodineveryPowerBuilderextensionmodulethatcontainsvisualclasses.WhenyouuseavisualextensioninaPowerBuilderapplication,thePBVMcallsthismethod.
SeeAlso
PBX_GetDescription
Exportedmethods:
PBX_DrawVisualObjectmethod
Description
DrawsavisualobjectinthePowerBuilderdevelopmentenvironment.
SyntaxPBX_DrawVisualObject(HDChDC,LPCTSTRclassName,constPBX_DrawItemStruct&
Argument Description
hDC Ahandletothedevicecontextoftheobject
classnameThenameofthevisualextensionobjecttobedrawn
property APBX_DrawItemStructstructurespecifyingthedisplaypropertiesoftheobject
ReturnValues
PBXRESULT.Thereturnvalueofthisfunctioniscurrentlyignored.
Examples
ThisisanextensionofasamplethatisavailableonthePowerBuilderCodeSamplesWebsite.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;
}
Usage
Inavisualextension,exportthisfunctionifyouwantthevisualcontroltobedrawninthedevelopmentenvironment.Ifyoudonotexportthefunction,youneedtoruntheapplicationtoseetheappearanceofthevisualcontrol.
SeeAlso
PBX_CreateVisualObjectPBX_DrawItemStructstructure
Exportedmethods:
PBX_GetDescriptionmethod
Description
PassesadescriptionofalltheclassesandmethodsinthePowerBuilderextensionmoduletoPowerBuilder.
SyntaxPBX_GetDescription()
ReturnValues
LPCTSTRcontainingthedescriptionofthemodule.
Examples
Thefollowingextensionmodulecontainsthreeclasses: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),andoneeventthatmapsaWindowsmessagedirectlytoaPowerBuilderevent(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;
}
Usage
YoumustimplementthismethodineveryPowerBuilderextensionmodule.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".
SeeAlso
PBX_CreateNonVisualObject
PBX_CreateVisualObjectPBX_InvokeGlobalFunction
Exportedmethods:
PBX_InvokeGlobalFunctionmethod
Description
ContainstheimplementationofoneormoreglobalfunctionsusedinthePowerBuilderextensionmodule.
SyntaxPBX_InvokeGlobalFunction(IPB_Session*pbsession,LPCTSTRfunctionname
Argument Description
pbsession ThisIPBsession
functionnameThenameoftheglobalfunction
ci ApointertoapreallocatedPBCallInfostructurecontainingtheparametersandreturnvaluesettingforthefunction
ReturnValues
PBXRESULT.PBX_OKforsuccess.
Examples
ThisPBX_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;
}
Usage
UsethisfunctioninaPowerBuildernativeclassthatusesglobalfunctions.ThefunctionisexportedfromthePowerBuilderextensionmoduleandisusedtoidentifyglobalfunctionsincludedinthemodule.LikeglobalfunctionsinPowerScript,globalfunctionsinPowerBuilderextensionscannotbeoverloaded.
SeeAlso
PBX_GetDescription
Exportedmethods:
PBX_Notifymethod
Description
Usedtoinitializeanduninitializeasession.
SyntaxPBXEXPORTPBXRESULTPBXCALLPBX_Notify(IPB_Session*pbsession,pbint
ReturnValues
PBXRESULT
Examples
ThissampleshowscodethatexportsPBX_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;
}
Usage
IfPBX_NOTIFYisexported,thePBVMcallsPBX_NotifyimmediatelyafteranextensionPBXisloadedandjustbeforethePBXisunloaded.Youcanusethisfunctiontoinitializeanduninitializeasession.Forexample,youcouldcreateasessionmanagerobject,andstoreitintheIPBsessionusingtheSetPropfunction.Later,youcoulduseGetPropto
obtainthesessionobject.
MethodexportedbyPowerBuilderVM
Description
ThismethodisexportedbythePowerBuilderVM:PB_GetVM
MethodexportedbyPowerBuilderVM:
PB_GetVMmethod
Description
PassestheIPB_VMinterfacetotheuser.
SyntaxPB_GetVM(IPB_VM**vm)
Examples
ThisexampleloadsthePowerBuilderVMandcallsthef_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("pbvm170.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;
}
Usage
ToloadthePowerBuilderVMandrunaPowerBuilderapplicationinathird–partyserverorapplication,youfirstcreateanIPB_VMobjectusingthePB_GetVMmethod.Then,createanIPB_SessionobjectwithinIPB_VM,usingtheapplication'snameandlibrarylistasarguments.
SeeAlso
CreateSession
PBNIToolReference
Aboutthischapter
ThischapterdescribestwotoolsprovidedwiththePBNISDK:Thepbsig170toolgetstheinternalsignatureofaPowerBuilderfunctionfromaPBLname.Thepbx2pbd170toolgeneratesaPBDfromaPBX.
WhenyouinstallPowerBuilder,thesetoolsareinstalledintheSDKsubdirectoryofyourPowerBuilder15.0directoryandinShared\PowerBuilder.
Contents
Topic
pbsig170
pbx2pbd170
pbsig170
Description
ThePowerBuilderfunctionsignatureistheinternalsignatureofaPowerBuilderfunctionthatisusedtoidentifypolymorphismfunctionsinaclass.Thepbsig170toolobtainsthesefunctionsignaturesfromaPBL.Inheritedfunctions
YoucanalsoobtainasignaturebyselectingthefunctionintheSystemTreeorBrowserandselectingPropertiesfromitspop-upmenu.Thepbsig170tooldoesnotreportthesignatureoffunctionsthatareinheritedfromanancestorobjectunlesstheyareextendedinthedescendant.Forsuchfunctions,youmustusethePropertiesdialogboxtoobtainthesignature.ThePropertiesdialogboxintheBrowseralsoallowsyoutoobtainthesignatureofPowerBuildersystemfunctions.
Syntaxpbsig170pbl_name
Examples
ThiscommandextractsfunctionsignaturesfromoneofthePBLsintheCodeExamplessampleapplication:pbsig170pbexamw1.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,thepbsig170toolreturnsthefollowingstring.Thefirstargumentisanunboundedarrayoftypes_sales_orderandispassedbyreference:/*IRCs_sales_order.[]YI*/
Usage
Thepbsig170toolgeneratesastringthatrepresentsthedeclarationandsignatureofallthefunctionsandeventsinthePBL,includingargumenttypes,returntypes,andpassingstyle.Eachfunctionandeventisfollowedbyacommentedstring.Youpassthecommentedstring,forexample,QSSinthefirstcommentinthepreviousexample,asthelastargumenttotheGetMethodIDmethod.Forexample,thefollowingoutputindicatesthatthefunctionreturnsanintegerandhasasingleintegerargumentpassedbyreference:/*IRI*/
PowerBuilderarraysPowerBuilderarraysareindicatedwithapairofsquarebrackets[]asasuffix.Forboundedarrays,thebracketsenclosethebounds./*IRCdatastore.RS[]SS*/
PowerBuildersystemorcustomclassAdditionallettercodesrepresentaPowerBuildersystemclassoracustomclass.TheletterCfollowedbythenameofaPowerBuilderobjectorenumeratedclassandaperiod(Cname.)representsanargumentorreturnvalueofthattype.Thefollowingtableshowshowtheoutputfrompbsig170mapsto
datatypesandotherentities.
Table8-1:Returnvalueandargumentrepresentationin
pbsig170output
Output Datatype
[] 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
pbsig170output
Prefix Meaning
None Passbyvalue
R Passbyreference
X Passasreadonly
V Variablearguments(varargs)
pbx2pbd170
Description
Thepbx2pbd170toolgeneratesaPowerBuilderdynamiclibrary(PBD)filefromaPowerBuilderextensionPBX.ThegeneratedPBDcanbeaddedtothelibrarylistofanyPowerBuilderapplicationtargetthatwillusetheobjectsandmethodsinthePowerBuilderextension.
Syntaxpbx2pbd170[+]des.pbdsrc1.pbx[src2.pbxsrc3.pbx...srcn.pbx]
Examples
ThisexamplegeneratesanewPBDtest.pbdfromtest.pbx.Theinputandoutputfilesareinthecurrentdirectory:pbx2pbd170test.pbdtest.pbx
ThisexampleappendsgeneratedinformationfromC:\myproject\src.pbxtoC:\mypbds\des.pbd.(Ifdes.pbddoesnotexist,itiscreated.)pbx2pbd170+C:\mypbds\des.pbdC:\myproject\src.pbx
ThisexamplegeneratesanewPBDD:\pbds\test.pbdfromallthePBXfilesintheC:\myprojectdirectory:pbx2pbd170D:\pbds\test.pbdC:\myproject\*.pbx
ThisexamplegeneratesPBDinformationfromallthePBXfilesintheC:\tempandD:\tempdirectoriesandappendstheinformationtotheexistinggeneratedPBDfileD:\pbds\test.pbd:pbx2pbd170+D:\pbds\test.pbdc:\temp\*.pbxd:\temp\*.pbx
Usage
YoucanimportanextensionintoaPowerBuilderlibraryusingtheImportPBExtensionpop-upmenuitemforthelibraryinthePowerBuilderSystemTree.PriortoPowerBuilder11.5,youhadtousethepbx2pbdnnntooltocreateaPBDfilefromaPBXfile,thenaddthePBDtothelibrarylistofyourPowerScripttarget.Thetoolisstillavailableinthisrelease.YoucanincludemultiplePBXsinasinglePBDfile.IfyouwanttoaddadditionalPBXstoanexistingPBD,usetheplus(+)signbeforethenameofthePBD.
Thepbx2pbd170toolisinstalledinthesystemPATHintheShared\PowerBuilderdirectorysoyoucaninvokeitinthedirectorywherethePBXsreside.IfyouspecifyanabsolutepathforthePBXfilewhenyougeneratethePBD,thePowerBuilderapplicationsearchesforthePBXonlyinthespecifiedpath.IfyoudonotspecifythepathforthePBXfile,thePowerBuilderapplicationsearchesthesystempathforthePBX.
AppendixThisappendixdescribeswizardsprovidedforMicrosoftVisualStudio.
AppendixA:UsingtheVisualStudioWizards
Aboutthisappendix
IfyouuseVisualStudio.NET2002or2003orVisualStudio2005,youcanuseawizardtocreateaPBNIextensionproject.Thewizardcreatesaprojectwith.cppand.hfilesthatcontainrequiredcodeaswellastemplatecodetohelpyougetstarted.CheckforwizardupdatesinthePBNIsectionofthePowerBuilderCodeSamplesWebsite.
Contents
Topic
Wherethewizardsareinstalled
GeneratingaPBNIproject
Settingprojectoptions
BuildingandusingthePBX
WherethewizardsareinstalledWhenyouinstallPowerBuilder,thesetupprograminstallsfourdirectoriesintothePowerBuilder15.0\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,browsetothelocationofthePowerBuilder15.0\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".