iWdZddlZddlZddlZddlmZ ddZdZdZdZ d Z d Z d Z e d kr6e \ZZZZZerejed eeeeeedSdS)ax Utility functions for writing out gateway C++ files This module will generate a C++/Python binding for a specific COM interface. Can be run from command line (passing required arguments) or the old way (start Python, import this module, change to the directory where the generated code should be written, and run the public function). This module is capable of generating both 'Interfaces' (ie, Python client side support for the interface) and 'Gateways' (ie, Python server side support for the interface). Many COM interfaces are useful both as Client and Server. Other interfaces, however, really only make sense to implement one side or the other. For example, it would be pointless for Python to implement Server side for 'IRunningObjectTable', unless we were implementing core COM for an operating system in Python (hey - now there's an idea!) Most COM interface code is totally boiler-plate - it consists of converting arguments, dispatching the call to Python, and processing any result values. This module automates the generation of such code. It has the ability to parse a .h file generated by the MIDL tool (ie, almost all COM .h files) and build almost totally complete C++ code. The module understands some of the well known data types, and how to convert them. There are only a couple of places where hand-editing is necessary, as detailed below: unsupported types -- If a type is not known, the generator will pretty much ignore it, but write a comment to the generated code. You may want to add custom support for this type. In some cases, C++ compile errors will result. These are intentional - generating code to remove these errors would imply a false sense of security that the generator has done the right thing. other return policies -- By default, Python never sees the return SCODE from a COM function. The interface usually returns None if OK, else a COM exception if "FAILED(scode)" is TRUE. You may need to change this if: * EXCEPINFO is passed to the COM function. This is not detected and handled * For some reason Python should always see the result SCODE, even if it did fail or succeed. For example, some functions return a BOOLEAN result in the SCODE, meaning Python should always see it. * FAILED(scode) for the interface still has valid data to return (by default, the code generated does not process the return values, and raise an exception to Python/COM N) makegwparsect|} tj||}|n#|wxYw|r|rd}n |r|sd}nd}|jdddkr'ddl}|jjj} |jjj } nt} t} ttj trtntjd|jd d } | d |jd |d | d|jz|r | | ||r | | || n#| wxYwttj trtntjd|jdd } | d|jd |d|rt%| ||rt'| || dS#| wxYw)aGenerate C++ code for a Python Interface and Gateway header_file_name -- The full path to the .h file which defines the interface. interface_name -- The name of the interface to search for, and to generate. bMakeInterface = 1 -- Should interface (ie, client) support be generated. bMakeGatewayInterface = 1 -- Should gateway (ie, server) support be generated. This method will write a .cpp and .h file into the current directory, (using the name of the interface to build the file name. zInterface and Gateway InterfaceGatewayNIEnumrPyz.cppwz// This file implements the  z? for Python. // Generated by makegw.py #include "shell_pch.h" zG#include "Py%s.h" // @doc - This file contains autoduck documentation z.hz// This file declares the z' for Python. // Generated by makegw.py )openrparse_interface_infoclosenamewin32com.makegw.makegwenummakegw makegwenum_write_enumifc_cpp_write_enumgw_cpp_write_ifc_cpp _write_gw_cppospathjoin directorygetcwdwrite _write_ifc_h _write_gw_h) header_file_nameinterface_namebMakeInterface bMakeGatewayoutput_directoryfin interfacedescwin32comifc_cpp_writer gw_cpp_writerfouts DC:\PYTHON\_runtimes\venv\Lib\site-packages\win32com/makegw/makegw.pymake_framework_supportr-7s$  C4^SII   ,&  ~bqbW$$))))!3F 2D '%   " 3II 5N).5N5N5N     D   &^  .2       Xn      , N4 + + +  + M$ * * *    )U9>>U>U>UVV   D   $>  ,0        * y ) ) )  ) i ( ( (  s#;AAE22F"AH==Ic  |d|jd|jd|jd|jd |jD]}|d|jz |d|jd|jd dS) Nz\// --------------------------------------------------- // // Interface Declaration class Pyz : public Pyz! { public: MAKE_PYCOM_CTOR(Pyz); static zT *GetI(PyObject *self); static PyComTypeObject type; // The Python methods z6 static PyObject *%s(PyObject *self, PyObject *args); z protected: Pyz(IUnknown *pdisp); ~Pyz(); }; )rrbasemethods)fr&methods r,rrsGG     &/^  !~   N    #    F T    GG ~       c  |j}|djd*i|jt jdd|j}|j|d}|jD]}|j|d<|djd*i|dx}x}x}x} x} x} x} } d}|jD]@} tj |}| dr| }|r|d | zd z||z }|d | zz }| |z } | |z } |p|}| |z } | |z } |\}}|r| d |zz } |d |zz },#tj$r}|d |j|j|d |jd|jd|jd|d|j|j|j| d|j|j|jz } |dz }|d|jzz }|d |jzz }| d|jd|jdz } Yd}~:d}~wwxYw|r|d|| || |d||j|| r?|d|| |d|dd|d<| |d<| |d<|d jd*i|dx}x} x}x}}|jD]}| d!s tj |}| }|rd||z }||z }| |z } |d |zz }||z }#tj$r>}|d"|j|j|Yd}~d}~wwxYw|r-|d#||||| n|d$|d%|d&|z|d'|z|jD]G}|d(|j|j|j|j|jH|j}|d)jd*it7dS)+Na/// --------------------------------------------------- // // Interface Implementation Py{name}::Py{name}(IUnknown *pdisp): Py{base}(pdisp) {{ ob_type = &type; }} Py{name}::~Py{name}() {{ }} /* static */ {name} *Py{name}::GetI(PyObject *self) {{ return ({name} *)Py{base}::GetI(self); }} z[a-z]) interfacenameptrr2z// @pymethod |Py{interfacename}|{method}|Description of {method}. PyObject *Py{interfacename}::{method}(PyObject *self, PyObject *args) {{ {interfacename} *p{ptr} = GetI(self); if ( p{ptr} == NULL ) return NULL; rin  , z %s; z// *** The input argument {} of type "{}" was not processed *** // Please check the conversion function is appropriate and exists! r z; PyObject *obz; z, // @pyparm |{}||Description for {} zL if (bPythonIsHappy && !PyObject_As{}( ob{}, &{} )) bPythonIsHappy = FALSE; Oz, &ob%sz PyObject_Free();  USES_CONVERSION; z: if ( !PyArg_ParseTuple(args, "{}:{}"{}) ) return NULL;  BOOL bPythonIsHappy = TRUE; z# if (!bPythonIsHappy) return NULL; rargsCOMcleanup cleanup_gilz HRESULT hr; PY_INTERFACE_PRECALL; hr = p{ptr}->{method}({argsCOM} ); {cleanup} PY_INTERFACE_POSTCALL; {cleanup_gil} if ( FAILED(hr) ) return PyCom_BuildPyException(hr, p{ptr}, IID_{interfacename} ); outK// *** The output argument {} of type "{}" was not processed *** // {} zE{} {} PyObject *pyretval = Py_BuildValue("{}"{}); {} return pyretval;z Py_RETURN_NONE; z } z-// @object Py%s|Description of the interface z-static struct PyMethodDef Py%s_methods[] = { z: {{ "{}", Py{}::{}, 1 }}, // @pymeth {}|Description of {} z {{ NULL }} }}; PyComTypeObject Py{name}::type("Py{name}", &Py{interfacebase}::type, sizeof(Py{name}), Py{name}_methods, GET_PYCOM_CTOR(Py{name})); )rrformat__dict__resubr0argsrmake_arg_converter HasAttribute GetFormatCharGetAutoduckStringGetParseTupleArg"DeclareParseArgTupleInputConverterGetParsePostCodeNeedUSES_CONVERSIONGetInterfaceArgCleanupGetInterfaceArgCleanupGILGetInterfaceCppObjectInfoerror_not_supportedraw_typetypeGetBuildForInterfacePreCodeGetBuildForInterfacePostCodeGetBuildValueArgr/locals)r1r&rr7strdictr2argsParseTuplerA formatCharscodePost codePobjects codeCobjectsrBrCneedConversionargargCvtval comArgNamecomArgDeclStringwhycodePre codeVarsPasscodeDecl formatChar interfacebases r,rrsV >DGG  ( ) ! !( ) ! !0 &2y~ . .C )s;;G#qq"K         %' ' ' '; ' 'L '  ' k;' G' GC& G$7<<##D)) J ..00CJv'?'?'A'A AD HIII#s* &$1H1H1J1J*JJ$(Q(Q(S(SS  F$;$;$=$==)7)W6;U;U;W;W6#@#@#B#BB#v'G'G'I'II /5/O/O/Q/Q, ,#A I0@$@@L4*,,2 G G G`gg#, PSXPPPP38PPPQQQDKK#(CH lssHchs" )ch"664#(?*FSXFFFFFF+ G.  , GG* + + +      M T TV[.      = GG5 6 6 6 GGH    GG; < < <$QRR[ $ !,          FHGG(G[G<(;  C##E**  $7<<#1133 L:-KvAACCCG C C E EEH D6+B+B+D+D$DDL I I K KKH2   cjj#,     + GG[bbg{L(     GG) * * *  GG < EFFFGG = DEEE#    J Q Q Y^V[&+v{      NMGG    XX       s3#D&G  KC8KK3BRS4S  Sc|jddkrd|jddz}n d|jz}|j}|jdks |jdkrd}n.|jddkrd|jddz}n d|jz}|d|d |d |d |d |d |d|d|d|d|jdkr4|d|j|jn|d|d|z|jD]}|d|jz|jrt|jddD],}|d|z-|jd}|d|z|d|d|dS)NrIPyGrIUnknown IDispatch PyGatewayBasezX// --------------------------------------------------- // // Gateway Declaration class z : public z , public z { protected: z(PyObject *instance) : z-(instance) { ; } PYGATEWAY_MAKE_SUPPORT2(r;z, IID_z) z2 // {} // *** Manually add {} method decls here z z // %s z STDMETHOD(%s)( z %s, z %s); z void); z}; )rr/rrGr0rKGetRawDeclarationr)r1r&gnamer base_namer2res r,rr]s~aC qrr** & >D~##y~'D'D# >!  # # qrr 22II .IGG     "   -1     $-  #  '+  37  ;D      ~##  E L L       GGK$ #&& $v{2333 ; &{3B3' A A s'<'<'>'>?@@@@+b/C GGNc&;&;&=&=> ? ? ? ? GG$ % % % %GGFOOOGGIIIIIr3c  |jddkrd|jddz}n d|jz}|j}|jdks |jdkrd}n.|jddkrd|jddz}n d|jz}|d|jD]}|d |d |jd |jr|jdd D]J}d |j}|d|d|dK|jd }d |j}|d|d|dn|d|dd}dx} x} } d} d} d}|jr|jD]}|dr-|dz }|j dkr|d|jz|dr tj |}| | }| p|} |r6||z }| |z } | d|zz } | |z } | |z } #tj$r}|d|j|j||d|j|j|j|d|j|j| d|jzz } |dz }| d|jzz } Yd}~d}~wwxYw| r|d || || |r|d!d"}nd#}|r |d$|d%| }n|}|d&|jd'|d(|| |r|d)|d*dx}x}x} }d} |jD] }|ds tj |}| | }|rc||z }|d|zz }||z }| |z } | p|} #tj$r?}|d+|j|j|Yd}~d}~wwxYw|r_t3|dkrd,}nd-}|r|||d.||||j| rG|d/|| |d0|jz|d1|d2dS)3NrrqrrrrsrtruzT// --------------------------------------------------- // // Gateway Implementation z STDMETHODIMP z::z( rvz][z /* [z] */ z, z) z void) z{ PY_GATEWAY_METHOD; r5rDz! if (%s==NULL) return E_POINTER; r8r;z// *** The input argument {} of type "{}" was not processed *** // - Please ensure this conversion function exists, and is appropriate // - {} z' PyObject *ob{} = PyObject_From{}({}); z? if (ob{}==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("{}"); z Py_DECREF(ob%s); r<z, ob%sr?z PyObject *result; z&resultNULLz, ""z HRESULT hr=InvokeViaPolicy("z", r>z if (FAILED(hr)) return hr; zD // Process the Python results, and convert back to the real params rE PyArg_ParsePyArg_ParseTuplezK if (!{}(result, "{}" {})) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("{}"); r@zB if (!bPythonIsHappy) hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("%s"); z Py_DECREF(result); z return hr; } )rr/rr0rKrinoutrwrMindirectionLevelrrLSetGatewayModerNrSrQr\GetBuildForGatewayPreCodeGetBuildForGatewayPostCoderWrGrXrYrPrRlen)r1r&rxrryr2reinoutstrcoutrkracodeVarsargStrrdr`rf formatcharrjresStr fullArgStrrbr_rgparseFns r,rrs~aC qrr** & >D~##y~'D'D# >!  # # qrr 22II .IGG #@'@'    {      ; #{3B3' P P99SY//N8NN#2G2G2I2INNNOOOO+b/Cyy++H GGJxJJc.C.C.E.EJJJ K K K K GGM " " " +,,,(***(X ;% 6{$ 6$ 6##E**RAID+q00 E PQQQ##D))66!,!?!D!D--///%+%9%9%;%; )7)W6;U;U;W;W%G':5K$(Q(Q(S(SSH"dV-D-D-F-F&FFF6#C#C#E#EE F$E$E$G$GG&:666u|| ##, GNN ##(CH _ff #&+ !$:SX$EE#s* (SX"55%66B  , GG* + + +     GG+ , , ,FFF  "=={==V==JJJ QQQQQQRRR  / . GG4 5 5 5 GGX   FH GK G, GNN{  ''..(;C@@F))+++ ..00CX#s* &$1H1H1J1J*JJ$(Q(Q(S(SS  F$;$;$=$==)7)W6;U;U;W;W"6GGgnnHclC {##q((+GG0G*GGL)))fmmnfk  9:::!!!Zk" GG, - - - %&&&&A@'@'s3B8KN* B?N%%N*)B!U  V4VVc&tdddS)Nzd:\msdev\include\objidl.hIStorage)r-rFr3r,testr)s9:FFFFFr3ctjd}|dddd|dd dd |d d d dd|ddd dd|ddd|\}}|rt d||jr$t j|js| dd|j s| dd|j|j |j |j |j pdfS)NzCOM interface wrapper generator) descriptionz --header_filez-fTzheader file (system) to parse)requiredhelpz--interface_namez-nzinterface name to search forz--no_create_interfacez-i store_falsecreate_interfacezdo not generate interface code)actiondestrz--no_create_gatewayz-gcreate_gatewayzdo not generate gateway codez--output_directoryz-oz!directory where to generate files)rz%Warning: Ignoring unknown arguments: rvzInvalid header file )statusmessagezInvalid interface name )argparseArgumentParser add_argumentparse_known_argsprint header_filerrisfileexitr!rrr$)parserrKunks r,parse_argumentsr2s  $1R S S SF 3R D46T    -     +  d)L''))ID# = ;c;;<<<  @27>>$2B#C#C@ 2'> ???  C 2'A BBB     %  r3__main__T)exist_ok)r r!r"r#r$)rrN)__doc__rrrIr5rr-rrrrrr__name__rr!rrrmakedirsrFr3r,rsP--^   UUUU~@dddN111hU'U'U'pGGG)))X zMK!1>9. I----$%'#"  r3