Sunteți pe pagina 1din 9

4/18/2017 APIStructures

AwaytoworkwithVisualFoxProandAPIStructures

Writtenby:EmanueleCerlini

July2004ReproductionProhibitedVersioneitaliana

Download:rpstruct.zip(lastupdate:April18,2006)

rAPIdStructureisanadapterforAPIStructuresanditrequiresVFP7orgreater.

Version1.10

Addedproperties:cExcludeList,lAutoFar
Addedparameter:nMemAddrtoWriteMemory()
RemovedtheobsoletelAllInCharStringparameterofSplitStruct().ItwasconsequenceofawrongwayofdeclaringcertainDlls.
Addedsupportformoreelementsinthesameline,fortheCstructures.
FixedbugwitharraysofBYTEwhenlAutoArray=.T.,fortheCstructures.
ReconsideredthecountofbytesfortheBitsstructures.

1.Introductionandadaptations
2.Hints
3.Properties
4.Functions
5.DataTypes
6.Samples

Introduction

Before starting, I would say straightaway that I do not know anything about Visual C++ and practically anything about Visual
Basic.ThelittleIknowaboutVisualFoxProallowsmetowonderhowcomesthatwehavecomebynowtoversion9.0andthere
isnointernalfunctionyetthatmanagesthestructureofdataworkingwiththeAPIfunctions(ApplicationProgrammingInterface).
Idevelopedmostofthefollowingworkbylogicaldeductionthereforeitislargelycorrigibleandintegrablefromthestudyof
documentation,fromtheexamplestakeninhttp://www.news2news.comandfromtheStructclass by Christof Lange (and Mark
Wilden,publishedin1999),peopleIthank.NowIaddalsoWilliamGCSteinford,ofwhomtheworkIhaveseenonlyafterthefirst
publication of this document, and the recent vfp2c32 of Christian Ehlscheid. Not for haughtiness or other demands, but just
becauseIbelievethatnowitispossibletosimplifyfurthertheinteractionofVFPwiththesestructures,Iallowedmyselftodevelop
aclass,entirelyinFox,thatIkindlyaskyoutohelpmetoimproveit.
MymainideaistotakewordforwordadefinitionofstructurewritteninC++orVB,totransferitinaFoxvariable(orinamemo
field),toimplementwithitaclasswherethestructuremembersarecreatedasnewpropertiesandfromheretopassandreceive
thedatafromDlls.Ofcoursealsothewidestsupportavailableisneeded:substructures,pointerstothememorybuffer,arraysof
characters,numbersandstructuresAndperhapsalsoanutilitythatcopieseasilyinprogrammingthemembersofstructure
Inshort,allthatisusefultoeliminatetheuneasinessfeelingthatmaytaketheuserwhenhelooksatthedocumentationofanAPI
functionandfindsoutthatsuchparameterisastructure.

PerhapsIexpressmyselfbetterwiththecodeofthemostbanalexample:
*!*codeforVFP7.00

LocalcMyDefAsString,;
oStructAsObject,;
cSysTimeAsString

*!*inizialize
SetProcedureTorpstructAdditive
oStruct=Createobject("rAPIdStructure")

*!*declarefunction
DeclareGetLocalTimeInWIN32API;
STRING@lpSystemTime

*!*copyandpasteSYSTEMTIMEstructurefromMSDNHelp
TEXTtocMyDefNOSHOW
typedefstruct_SYSTEMTIME{
WORDwYear;
WORDwMonth;
WORDwDayOfWeek;
WORDwDay;
WORDwHour;
WORDwMinute;
WORDwSecond;
WORDwMilliseconds;
}SYSTEMTIME,*PSYSTEMTIME
ENDTEXT

WithoStruct
*!*Loadit
.LoadCDef(m.cMyDef)

*!*Buildastring
cSysTime=.MakeStruct()

*!*CallDll
GetLocalTime(@cSysTime)

http://www.foxitaly.com/ecerlini/struttureapi_en.html#intro 1/9
4/18/2017 APIStructures
*!*Splittheresultinmembers
.SplitStruct(m.cSysTime)

*!*Theresultishere
?"Year",.wYear
?"Month",.wMonth
?"DayOfWeek",.wDayOfWeek
?"Day",.wDay
?"Hour",.wHour
?"Minute",.wMinute
?"Second",.wSecond
?"Milliseconds",.wMilliseconds

*!*Using.ClipMembers()topasteherethemembers'name

Endwith

ClearDlls"GetLocalTime"
oStruct=.Null.

*!*endexample

Ofcourseitisnotalwayssosimple.Inparticular:

Tosolvesomehowtheproblemofdatatypesvariety,IchosetotakeanofficiallistfromMSDN>PlatformSDK: Win32 API >


DataTypes,withsomechanges.ThefunctionDataTypes()returnsthelistofthedatarecognizedinbasetotheirlengthinbit(8,
16,32and64),fortheClanguage.
AsfarasVisualBasicdataareconcerned,thefollowingareaccepted:
BOOLEAN,BYTE,DOUBLE,INTEGER,LONG,STRING,SINGLE

Iconsideranydatanotrecognizedamongthese,inthe2languages,asasubstructureandsoitbringsaboutthecreationofa
rAPIdStructure internal object to load with its own structure definition, if it is not among the ones included in the DataTypes()
returnedstringandtheyareenabled.IflUnknownAsStructis.F.,instead,theclassmarkseachnotrecognizeddatatypesuchas
32 bit number. It is necessary to see the guide of each structure to know which data are therein. It is also possible to use
ClipMembers()withtheparameters1,2or3toknowhowandwhichdatatypeshavebeenrecognizedbytheclass.

Inthiscase:
typedefstruct_SHFILEOPSTRUCT{
HWNDhwnd;
UINTwFunc;
LPCTSTRpFrom;
LPCTSTRpTo;
FILEOP_FLAGSfFlags;
BOOLfAnyOperationsAborted;
LPVOIDhNameMappings;
LPCSTRlpszProgressTitle;
}SHFILEOPSTRUCT,*LPSHFILEOPSTRUCT;

wefindtheline
FILEOP_FLAGSfFlags;

where FILEOP_FLAGS is not a substructure but just a nonrecognized data type whose length is 2 bytes (please refer to
Shellapi.h:typedefWORDFILEOP_FLAGS).Therefore,beforeloadingall,let'schangethatlinewiththisone:

WORDfFlags;

andtheproblemisresolved.

Forpointersinmemory,forthoseregardingtextlikeLPTSTRandLPWSTR(thosewithSTRorCHARintheend),iflAutoMemory
is.T.,itcanbeenteredastringininput,obtainingitdirectlyinoutput.Intheothercasesinputeoutputarenumeric,alsoinorder
to the substructures in memory, directly managed with the functions WriteMemory(), etc. Also, if lAutoFar = .T., my special
support for Windows Sockets Structures exists for reading of CHAR FAR * as LPTSTR and CHAR FAR * FAR * as array of
pointerswithoutdirectconversionintext(abovethislastlAutoMemorydoesn'taffect).

In the following case we have 3 substructures FILETIME which are loaded automatically as they have lAllowIntStruct=.T.,
otherwisetheyhavetobeloadedbystrucure1.member.LoadCDef(m.cVariableDef),thatistosay:
oStruct.ftCreationTime.LoadCDef(m.cFileTime)

wherem.cFileTime is a variable containing the definition of FILETIME structure. It will then be possible to access members of
substructureinthisway:
?oStruct.ftCreationTime.dwLowDateTime

typedefstruct_WIN32_FIND_DATA{
DWORDdwFileAttributes;
FILETIMEftCreationTime;
FILETIMEftLastAccessTime;
FILETIMEftLastWriteTime;
DWORDnFileSizeHigh;
DWORDnFileSizeLow;
DWORDdwReserved0;
DWORDdwReserved1;
TCHARcFileName[MAX_PATH];
TCHARcAlternateFileName[14];
}WIN32_FIND_DATA,*PWIN32_FIND_DATA;

butinthislastexamplewehave2TCHARarraysalso:
http://www.foxitaly.com/ecerlini/struttureapi_en.html#intro 2/9
4/18/2017 APIStructures
TCHARcFileName[MAX_PATH];
TCHARcAlternateFileName[14];

IftheyarerepresentedbyaconstantsuchasMAX_PATH,itmeansthatinaheaderfilethereis:
#defineMAX_PATH260

andso,beforeloadingthestructure,wereplacethatconstantmanually:
TCHARcFileName[260];

Thistopicisvalidalsoforexpressionssuchas(0to31):itmustbereplacedwithanuniqueintegervalue(32).
Anydatatypecanberepresentedwitharrays,includingsubstructures.
For C language, in case lAutoArray is .T., the class treats as ANSI text strings the arrays of BYTE, BCHAR, CHAR, TBYTE,
TCHAR, UCHAR for Unicode text, arrays of WCHAR. For Visual Basic, ANSI text for the arrays of BYTE or STRING of
INTEGERforUnicode.Theclassdoesn'tacceptarrayswith0elements.
If these data are not in array format, their numerical value is reported (except for Visual Basic STRING). It exists also the
possibilityforanAPIfunctiontocalldirectlyanarrayofdataorofstructuresasparameter:theInitAPIArray()functiontreatsthese
as if they are a structure with an array composed by a single data type (or substructure) and it produces a passable and
receivablestringfortheDlls.

Going back over the pointers into memory, how previously pointed, there is also the possibility to have substructures in a
memoryblock:
typedefstruct_JOB_INFO_2{
DWORD JobId;
LPTSTR pPrinterName;
LPTSTR pMachineName;
LPTSTR pUserName;
LPTSTR pDocument;
LPTSTR pNotifyName;
LPTSTR pDatatype;
LPTSTR pPrintProcessor;
LPTSTR pParameters;
LPTSTR pDriverName;
LPDEVMODE pDevMode;
LPTSTR pStatus;
PSECURITY_DESCRIPTORpSecurityDescriptor;
DWORD Status;
DWORD Priority;
DWORD Position;
DWORD StartTime;
DWORD UntilTime;
DWORD TotalPages;
DWORD Size;
SYSTEMTIME Submitted;
DWORD Time;
DWORD PagesPrinted;
}JOB_INFO_2,*PJOB_INFO_2;

herewehavetwoelementsthatpointtooneDEVMODEandoneSECURITY_DESCRIPTOR(notreportednow)inthememory.
Inordertopreparethemainstructurewereplacethereferencesatthetwostructures
LPDEVMODEpDevMode;
PSECURITY_DESCRIPTORpSecurityDescriptor;

withdatatypeHGLOBAL

HGLOBALpDevMode;
HGLOBALpSecurityDescriptor;

inordertobeabletostorethenumericvaluewhichrepresentstheaddressintomemory.Ifafterwards,forinstance,wewuold
alsouseDEVMODE,wecreateaseparatedobjectrAPIdStructureintowhichweloadandsetthislaststructure,writethestringof
it,obtainedbyMakeStruct()intobufferwithWriteMemory()andstoretheresultintomember.pDevMode.Nowthemainstructure
JOB_INFO_2willuseitdirectly.InordertofreetheallocatedmemoryitwillbenecessarytoactcallingthefunctionFreeMemory()
becausethisdoesn'thappenautomatically.ItisneededtosetattentiontothosewritteninVisualBasicbecauseany,asthatofthe
preceding example, seems to manage the memory handles directly as incorporated structures, while for other, like
CHOOSEFONT,theyreportthedatatyperepresentingthehandleandwithwhichone it is needed to replace the name of the
structure:LONG.

DefinitionsintheprecedingstructurewritteninVisualBasic:
pDevModeAsDEVMODE
pSecurityDescriptorAsSECURITY_DESCRIPTOR

correctbeforetheloadingintotheclass:

pDevModeAsLong
pSecurityDescriptorAsLong

inalternativewecouldsetlUnknownAsStructto.F.,butifwefindamedleyofsubstructuresnormallyincorporatedandotherinto
memory, the manual substitution of the data type before the loading is the only way. I have not found a better way in order to
automatizethisparticularityofthestructures,consideringthepossiblevariants.

IflAutoUnicodeConvis.T.,theconversionofUnicodetextstringsisautomatic.

IncaseofkeywordUnioninastructure:

http://www.foxitaly.com/ecerlini/struttureapi_en.html#intro 3/9
4/18/2017 APIStructures
typedefstruct_PROCESS_HEAP_ENTRY{
PVOIDlpData;
DWORDcbData;
BYTEcbOverhead;
BYTEiRegionIndex;
WORDwFlags;
union{
struct{
HANDLEhMem;
DWORDdwReserved[3];
}Block;
struct{
DWORDdwCommittedSize;
DWORDdwUnCommittedSize;
LPVOIDlpFirstBlock;
LPVOIDlpLastBlock;
}Region;
};
}PROCESS_HEAP_ENTRY,*LPPROCESS_HEAP_ENTRY;

Welookattheguidetoknowwhichpartisimplementedand,bymanualintervention,weremovethenoninterestingone:

typedefstruct_PROCESS_HEAP_ENTRY{
PVOIDlpData;
DWORDcbData;
BYTEcbOverhead;
BYTEiRegionIndex;
WORDwFlags;
union{
struct{
DWORDdwCommittedSize;
DWORDdwUnCommittedSize;
LPVOIDlpFirstBlock;
LPVOIDlpLastBlock;
}Region;
};
}PROCESS_HEAP_ENTRY,*LPPROCESS_HEAP_ENTRY;

orwespecifythemembersthatmustbeexcludedinthecExcludeListproperty:

oStruct.cExcludeList="hMemdwReserved"

Finallyitisnecessarytonoticethat,ifastructuremembercorrespondstoapropertyalreadyexistingintheclass,whileloading,a
character _ (underscore) will be added at the beginning of the new property. This is the case of RECT structure (or RECTL)
havingleftandtopasmembers:

typedefstruct_RECT{
LONGleft;
LONGtop;
LONGright;
LONGbottom;
}RECT

Inordernottoconfusethemwiththenativeproperties,thenewoneswillbereportedthiswayintheclass:

WithoStruct
._left
._top
.right
.bottom
EndWith

Ihopethisworkwillbehelpfultosomebody.Ijustremindthatthisisanadaptationandthat,evenifitconcernsmanyofthemost
commonstructures,itisnotpossibletodemandmiracles.

Hints

SETCOMPATIBLEmustbeOFF.
SETFIXEDOFFisrecommended.

Checkalwaysthefinalsemicolon()fortheelementsoftheC++structures.

Userptest_en.prginordertotestquicklytheloadingofthestructures.

DocumentationofrAPIdStructureclassinrpstruct.prg
Fortheinitialization:
SetProcedureTorpstructADDITIVE
oStruct=CreateObject("rAPIdStructure")

PUBLICPROPERTIES(betweenbracketsthedefaultvalue)

PropertieslAllowIntStruct,lAutoArray,lAutoFar,lBoolNumeric,lSplit64bitandlUnknownAsStructcanbesetonlybeforeloadinga
structuredefinitionorbeforetocreateanAPIarray.
Classesofthesubstructuresinheritthepropertiessettingsofthemainclass.
ThepropertiescDoubleNullList,cExcludeList,nPaddingandvStopAtarenothereditaryandareappliedonlytotheirownstructure

http://www.foxitaly.com/ecerlini/struttureapi_en.html#intro 4/9
4/18/2017 APIStructures
ortothefirstlevelinanarrayofstructures.

Itispossibletoloadjustonestructureatatime.

cDoubleNullList(="")
Containsthelist,semicolonseparated(),ofthemembersthatSplitStruct()mustreadfromthememoryasdoubleNullterminated
strings.

cExcludeList(="")
Specifies a semicolonseparated list () of the members that are excluded from the structure processing. Expressly for the
structuresthatuse"Union"parts.

cStructure(="")
Containsthenameoftheloadedstructure.

lAllowIntStruct(=.T.)
Allowstheautomaticloadingoftheinternalstructures(seeDataTypes("IS"))

lAutoArray(=.T.)
Managesthearraysof8or16bitdataautomaticallyastextstrings,or,ifthispropertyis.F.,itconsidersthemastheotherarrays
reportingthenumericalvalueofeachelement.

lAutoFar(=.T.)
IfitisFalse(.F.),disablestheautomatismforthedatatypesCHARFAR*andCHARFAR*FAR*,recognizingthemassimply
pointers.

lAutoMemory(=.T.)
Inordertothepointersinmemory,ifthisvalueis.T.,theclassallowstheautomaticreading/writingintobufferwithtextstrings,
otherwisetheclassacceptsandreturnsonlynumericalvalues.

lAutoUnicodeConv(=.T.)
IfTrue(.T.),convertsautomaticallytheANSIstringstoUnicodeandviceversa,inInputandOutput.

lBoolNumeric(=.T.)
If True (.T.) indicates that Boolean values are represented as numerical (0 = False, True in the other cases) if False (.F.) the
Booleanvaluesarelogical(.T.o.F.).

lSplit64bit(=.T.)
OnlyforC++languagedatatypes.Forthe64bitintegervalue,ifthisvalueis.T.,theclasscreatesasubstructurethatseparates
theseintwo32bitportions.TheelementswillhavethenamesofLowPartandHighPart. The formula in order to calculate the
entirevaluewouldbe(HighPart*(0xFFFFFFFF+1))+LowPart.

lUnknownAsStruct(=.T.)
ManagesinautomaticwaythesubstructurescreatingforeachnotrecognizeddatatypeanobjectrAPIdStructure.Ifthisvalueis
.F., it recognizes the data type as HGLOBAL (numeric, unsigned, 4 bytes) in order to the definitions in C language, or LONG
(numeric,signed,4bytes)forthoseinVisualBasic.

nError(=0)
Containstheinternalcodeinordertothelasterroroccours.
Thesearetheerrorcodes:

0 noerror
11 parametersnotcorrect
301 structurenotloaded
302 structurealreadyloaded
303 definitionofstructurenotvalid
304 nameofstructureismissing
305 invalidarrayinstructure
306 nomembersloaded
307 invaliddatatypeinamember
308 errorinastructureofsecondarylevel
309 DLLerrorreading/writingmemory
310 nopointerstored
311 membernamenotexisting
312 invalidmemberindex
313 thememberisnotapointer
314 thestringdoesn'thavepointerinmemory

nPadding(=0)
AdjustsartificiallythesizeofthestructureaddingthespecifiednumberofNullcharacters.Whetherthisvalueis1,theclassadds
automaticallythenecessarycharactersroundingupthesizetothenearestmultipleof4.Thissettingoutismostcommonforthe
structuresthatrequireit(seealsothefilecorrect.rtf).

vStopAt(=0)
Indicatesthename(character)orthenumber(numericandfaster)ofthelastelementtoelaborate.Itisneededtoconsiderthe
membersthatcontainarraysorsubstructuresasasingleelement.Thissupportisforthemultiversionstructures,forexample

http://www.foxitaly.com/ecerlini/struttureapi_en.html#intro 5/9
4/18/2017 APIStructures
theonesthatchangetheirdimensionfromanoperativesystemtoanother.Thenumberofelementincludesalsothemembers
thatcouldbelistedincExcludeList.

PUBLICFUNCTIONS(betweenbracketsthevalidparameters)

ForallthefunctionsisvalidthetopicthatiftheoperationsucceedsthepropertynErrorwillhavevalue0,otherwiseitwillreport
theerrorcode.
ThefunctionsCalculateBytes(),MakeStruct(),SplitStruct()and,with0or2asparameter,ClipMembers()havenegativeresultifall
thepossiblesubstructureshavenotbeenloaded.

CalculateBytes
Calculatesandreturnsthesize,inbytes,ofthestructure.
Ifthefunctionfails,thereturnvalueis0.

ClipMembers(nMode)
Utilityfordevelopers.ItcopiestotheClipboardthenamesofthestructure'smembers,withadotatthebeginning,readytopaste
itintoacommandWITH...ENDWITH.
In order to the parameter nMode (numeric and optional): if the value is 1, forces the copy of the members also if the sub
structureshavenotbeenloadedifthevalueis2,addsacommenttoeachmemberwiththedescriptionofhow the class has
recognizedit,butitdoesn'tforcesthecopywithvalue3,forcesthecopyandaddsthecommentwiththedescription.Withoutor
withanyothervalue,copiesthenamesofthemembers,withoutcommentsandonlyifallthesubstructuresarecorrectlyloaded.
Ifthefunctionfails,thereturnvalueis.F.

DataTypes(cType)
Returnsthelistofthedatatypesautomaticallyrecognizedbytheclassandoftheinternalstructures.ForClanguage,thelistis
separatedinbasetothelengthinbitoftherepresenteddata,passingasparameters8,16,32or64forVisualBasicwith"VB"
parametertheresultwillbeasinglelistoftherecognizeddatatypes.Inalltheothercasesthereturnedlististhatoftheinternal
structuresautomaticallyrecognizediflAllowIntStructis.T.
The parameter cType (character or numeric and optional) must contain the indication for the list to obtain. Please, for the
completelistofsupporteddatatypesseeattheendofthisdocumentation.

FlagTest(nIntValue,nFlag)
Checkswhetheroneormoreflags(bitsthataresetto1)existinadeterminedfieldornumericvalueand,whensucceeding,it
returnsTrue(.T.).ThefunctionissimilartoBITTEST()butitdoesn'trequirethepositionofthebittotestanditalsoworkswith
flagscomposedbymorebits.
TheparameternIntValue(numeric)indicatesthevaluethatcouldcontaintheflags.
TheparameternFlag(numeric)specifiesthenumbercomposedbyoneormoreflagsofwhichverifythepresenceinnIntValue
(nFlag=0returnsalways.T.).
Ifthefunctionfails,thereturnvalueis.F.

GetPtr(cMemberName,nIndex)
Returns the pointer of a text string from the memory. The function operates only with the members of the class in which it is
contained.Inbasetothelastofthetwofunctionsalreadycalled,thereturnedpointeristhatofthestringwrittenbyMakeStruct()
orthatreportedbySplitStruct().
TheparametercMemberName (character) must contain the name of the structure member from which has to be returned the
pointer.
TheparameternIndex(numericandoptional)specifiestheindexnumberoftheelementinanimprobablearrayofpointers.
Ifthefunctionfails,thereturnvalueis0.

InitAPIArray(cDataType,nElement,cElementName)
CreatesanarrayforAPIfunctions,composedbyanuniquedatatypeorstructure,andprocessesitlikeasinglestructure.Ifdata
typeisastructure(notinternal),itisafterwardsnecessarytoloadthedefinitionofthestructureintoeachmemberofthearray.
ThisfunctionrespectsalltherulesofLoadCDef()oLoadVBDef().OnlythedatatypesofClanguagecouldbeloadedlikesingle.
TheparametercDataType(character)mustcontainthenameofdatatypeorstructuretoload.
TheparameternElement(numericandoptional)mustcontainthenumberofelementsforthearray.Ifitisempty,thearraywill
haveanuniqueelement.
TheparametercElementName(characterandoptional)mustcontainthenameofthenewpropertywheretheclasswillstorethe
array.Ifitisempty,thepropertytakesthenameofthedatatype.
Ifthefunctionfails,thereturnvalueis.F.

LoadCDef(cDefStruct,lAnsi2Wide)
LoadsadefinitionofstructurewritteninC++language.
TheparametercDefStruct(character)mustcontainthedefinition.
The parameter lAnsi2Wide (logical and optional), if True (.T.) loads a declared ANSI structure as if it is Unicode (TCHAR
>WCHAR,LPTSTR>LPWSTR,...).
Ifthefunctionfails,thereturnvalueis.F.

LoadVBDef(cDefStruct)
LoadsadefinitionofstructurewritteninVisualBasiclanguage.
TheparametercDefStruct(character)mustcontainthedefinition.
Ifthefunctionfails,thereturnvalueis.F.

MakeStruct(lAllZero,nLength)
Returnsacharacterstringassemblingthemembersofthestructure.ThisstringisreadytobepassedtotheAPIfunction.
IflAutoMemoryis.T.andatexthasbeenintroducedinamemberthatpointstothememory,thisfunctionallocatesthememory,
writingthestring.ResetDatafreesitautomatically.
IftheparameterlAllZero(logicalandoptional)is.T.,itreturnsastringofcharactersChr(0)withoutestimatingthecontentofthe
variousmembers,earninginspeed.ThisstringisproperfortheAPIfunctionsthatdon'trequirevaluesininput.
TheparameternLength(numericandoptional)indicatesthelengthofthereturnedstringaddingcharacters(Chr(0))attheendifit
isnecessary.ThisisignoredifhisvalueissmallthanthevaluereturnedbyCalculateBytes().
Ifthefunctionfails,thereturnvalueisanemptystring(="").

http://www.foxitaly.com/ecerlini/struttureapi_en.html#intro 6/9
4/18/2017 APIStructures
ResetClass
Resetstheclassbringingitbacktotheinitialcondition,beforeloadingadefinitionofstructure(butonlysinceVFP8itremoves
thepropertiesaddedintheclass).
Thisfunctiondoesn'tmodifythesettingofcDoubleNullList,cExcludeList,lAllowIntStruct,lAutoArray,lAutoMemory,lBoolNumeric,
lSplit64bit,lUnknownAsStruct,nPaddingandvStopAt.
Ifthefunctionfails,thereturnvalueis.F.

ResetData
Setszerothedataofthesinglememberscarringthemtotheemptyvalue.Italsocleansthememoryallocatedbytheclass(not
bytheAPIfunctions),ifpossible.However,thisfunctionisrecommendedeverytimethatistobeenteredinreadingorwritingto
thememorybuffer.DestroyEventcallsthisfunctionifitisnecessary.
Ifthefunctionfails,thereturnvalueis.F.

SplitStruct(cCharString)
RedistributesthecharacterstringreceivedbytheAPIfunctioninthemembersoftheclass.Automaticallyconvertsthedatainthe
typerequestedbytheirreading.
TheparametercCharString(character)mustcontainthestringofthestructure.
(TheobsoleteparameterlAllInCharString(logical)hasbeenremoved).
Ifthefunctionfails,thereturnvalueis.F.

Memorymanagement
AllocateMemory(nBytes)
Allocatesanumberofbytesfromtheheapandreturnthehandletothenewlyallocatedmemoryobject.WriteMemory()callsthis
functionautomatically.
TheparameternBytes(numeric)specifiesthenumberofbytestoallocate.
Ifthefunctionfails,thereturnvalueis0.

FreeMemory(nMemHandle)
Freesthespecifiedglobalmemoryobject.
TheparameternMemHandle(numeric)indicateswhichisthehandletofree.
Ifthefunctionfails,thereturnvalueis.F.

GetMemorySize(nMemHandle)
Retrievesthecurrentsize,inbytes,ofthespecifiedglobalmemoryobject,wheneverpossible.
TheparameternMemHandle(numeric)indicateswhichisthehandletoread.
Ifthefunctionfails,thereturnvalueis0.

ReadMemory(nMemAddr,nSizeRead,lUnicode,lDoubleNull)
Returnsthecontentsofapointerintomemoryasastring.
TheparameternMemAddr(numeric)specifiesthepointertoamemoryaddress.Iftheotherparametersaremissing,itreadsup
tothefirstnullcharacter.
TheparameternSizeRead(numericandoptional)specifiesthenumberofbytestoread.Ifthisvalueispresentandgreaterthan
0,theparameterslUnicodeandlDoubleNullareignored.
The parameter lUnicode (logical and optional) if True (.T.) considers the string as Unicode and, if lAutoUnicodeConv is .T., it
convertstheUnicodetexttoANSI.
TheparameterlDoubleNull(logicalandoptional),ifTrue(.T.)specifiesthatthestringtoreadistheoneterminatingwithadouble
Nullcharacterinsteadthanoneonly.
Ifthefunctionfails,thereturnvalueisanemptystring(="").

WriteMemory(cMemString)
Writesastringintomemoryandreturnstheaddress.
TheparametercMemString (character), with length better than 0, must contain the string to write. Please, pay attention to the
documentationofthestructuretoknowhowtoterminatethestringwiththeadditionofoneormorenullcharactersChr(0).
TheparameternMemAddr(numericandoptional)indicatesthememoryaddressinwhichtowritedirectly.Theusethisparameter
ispotentiallydangerousfortheapplication.Please,seethecommandSYS(2600)inFoxHelp.
Ifthefunctionfails,thereturnvalueis0.

Numericconversion
ThesefunctionsresentoftheVFPlimitsandthevaluesoutofrangearenotverified.

Char2Float(cCharFloat)
Convertsabinarycharacterrepresentationtoafloatingpoint(IEEE)number.
TheparametercCharFloat(character)mustcontain4or8charactersandthedecimalplacesdisplayedinresultarerespectively
6or15.
Ifthefunctionfails,thereturnvalueis0.

Char2Num(cCharInt,lSigned)
Convertsabinarycharacterrepresentationtoanintegervalue.
TheparametercCharInt(character)specifiesthebinarycharacterrepresentationtoconvert.
TheparameterlSigned(logicalandoptional)indicatesifthereturnednumbercouldbenegative.
Ifthefunctionfails,thereturnvalueis0.

Float2Char(nFloat,lDouble)
Convertsafloatingpoint(IEEE)numbertoabinarycharacterrepresentation.
TheparameternFloat(numeric)specifiesthefloatingpointnumbertoconvert.

http://www.foxitaly.com/ecerlini/struttureapi_en.html#intro 7/9
4/18/2017 APIStructures
TheparameterlDouble(logicalandoptional)indicatesiftherepresentedresultisFloatorDouble(4or8characters).
Ifthefunctionfails,thereturnvalueisanemptystring(="").

Num2Char(nIntValue,nChar)
Convertsanintegervaluetoabinarycharacterrepresentation.
TheparameternIntValue(numeric)specifiestheintegervaluetoconvert.
The parameter nChar (numeric and optional) indicates the length in characters of the returned character string. When it is
missing,theresultantstringwillbelong4bytes.
Ifthefunctionfails,thereturnvalueisanemptystring(="").

SupportedDataTypesbytheclass(returnedbyDataTypes())
8bitC(equaltoDataTypes("8"))

BYTE BCHAR CHAR TBYTE TCHAR UCHAR

16bitC(equaltoDataTypes("16"))

ATOM LANGID SHORT USHORT WCHAR WORD

32bitC(equaltoDataTypes("32"))

BOOL BOOLEAN COLORREF DWORD DWORD_PTR DWORD32 FLOAT HACCEL HANDLE


HBITMAP HBRUSH HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK
HDROP HDWP HENHMETAFILE HFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON
HIMAGELIST HIMC HINSTANCE HKEY HKL HLOCAL HMENU HMETAFILE HMODULE
HMONITOR HPALETTE HPEN HRGN HRSRC HSZ HWINSTA HWND INT
INT_PTR INT32 IPADDR IPMASK LCID LCSCSTYPE LCSGAMUTMATCH LCTYPE LONG
LONG_PTR LONG32 LPARAM LPBOOL LPBYTE LPCOLORREF LPCSTR LPCTSTR LPCVOID
LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR LPVOID LPWORD
LPWSTR LRESULT PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWCH
PCWSTR PDWORD PFLOAT PHANDLE PHKEY PINT PLCID PLONG PSHORT
PSTR PTBYTE PTCHAR PTSTR PUCHAR PUINT PULONG PUSHORT PVOID
PWCHAR PWORD PWSTR REGSAM SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SIZE_T SSIZE_T
UINT UINT_PTR UINT32 ULONG ULONG_PTR ULONG32 USHORT VOID WPARAM

64bitC(equaltoDataTypes("64"))

DWORD64 DWORDLONG INT64 LONG64 LONGLONG QWORD UINT64 ULONG64 ULONGLONG

VisualBasic(singlelist,equaltoDataTypes("VB"))

BOOLEAN BYTE DOUBLE INTEGER LONG STRING SINGLE

InternalStructures(insideintheclass,equaltoDataTypes("IS")orDataTypes().Itispossibletocreatethemdirectlyinthemain
classpassingjustthenameinsteadofthecompletedefinition,ignoringthelAllowIntStructsetting)

FILETIME POINT(orPOINTL) RECT(orRECTL) SYSTEMTIME

Includedsamples
Simplestructures:createprocessVB.prg,...
Substructure:getwindowplacementVB.prg,...
Pointersintomemory:getstartupinfoVB.prg,...
Constantsandnonsupportedexpressions:findfirstfileC.prg,sendmessageVB.scx,...
Nonrecognizeddatatypewhenitisnotasubstructure:shfileoperationC.prg,...
64bitdatatypes:globalmemorystatusexC.prg,...
Arrayastext:gettimezoneinformationC.prg,...
Union:shellexecuteexC.prg
Structuresinmemoryandcomplex:gethostbynameC.prg,getprinterVB.prg,...
APIarrayofsingledatatypesandstructures:polypolygonC.scx,enumprinterdriversC.prg,...
Arrayofarrays:devicecapabilitiesC.prg
Membersinbits:shgetsettingsC.prg,...
GetPtr:getopenfilenameC.prg,...
DoubleNull:getprinterdriverC.prg
Multiversionstructures:rasgetconnectionstatisticsC.scx,...

Otherexamples:faxsenddocumentC.prg,mapisendmailC,setprinterVB.prg,...

http://www.foxitaly.com/ecerlini/struttureapi_en.html#intro 8/9
4/18/2017 APIStructures
"Sectionforwhoeverreadsthedetectivestorybeginningfromthelastpage..."

Allbrandorproductnamesaretrademarksorregisteredtrademarksoftheirrespectiveholders.

The class has been tested with Windows XP Professional and Visual FoxPro 8 SP1 (with backward compatibility to VFP 7,
recompilingit).Notallthedatatypes,recognizedbytheclass,havebeentested.

Theclassisdeprivedofeachwarrantyorrefundfordirectorindirectdamagestowhoeveruseitand/ortothirdusers,itis"asis"
andeachmodificationisunderexclusiveresponsibilityofwhoeveroperatesit.
Theclassisfreeandwithoutroyalties,itcouldalsobedistributedwiththecodeanddecompiled.

Beclementwiththecritics:IabandonedschoolwhenIwas16yearsoldandsincearoundtwentyyearsI'vebeenworkingwith
cattle(itistrue,notascarceconsiderationofmycolleagues...)inthenatureoftheemilianacountry.

Thankyouforhavingreaduptohereandtothosepeoplewhowillmakeuseofmywork.Youcouldsendbugs(deadoralive)
andcommentstomyemailaddress.

IthankLauraandSaraforthistranslation(...andmyselfinordertotechnicalandgrammaticalerrors)
Article:EmanueleCerlini,SabbioneReggioEmilia
Breeder,hobbydeveloper

July2004ReproductionProhibited

Download:rpstruct.zip


FoxProeVisualFoxProareregisteredtrademarksofMicrosoftCorporation

Date:July302004
webmaster@foxitaly.com

dal22Giugno1999

http://www.foxitaly.com/ecerlini/struttureapi_en.html#intro 9/9

S-ar putea să vă placă și