Ejemplo n.º 1
1
// @pymethod (int, ...)/int|PyIDispatch|GetIDsOfNames|Get the DISPID for the passed names.
PyObject *PyIDispatch::GetIDsOfNames(PyObject *self, PyObject *args)
{
	// @rdesc If the first parameter is a sequence, the result will be a tuple of integers
	// for each name in the sequence.  If the first parameter is a single string, the result
	// is a single integer with the ID of requested item.
	UINT i;

	// @pyparm string|name||A name to query for
	// @pyparmalt1 [string, ...]|[name, ...]||A sequence of string names to query
	// @comm Currently the LCID can not be specified, and  LOCALE_SYSTEM_DEFAULT is used.
	int argc = PyTuple_GET_SIZE(args);
	if ( argc < 1 )
		return PyErr_Format(PyExc_TypeError, "At least one argument must be supplied");

	LCID lcid = LOCALE_SYSTEM_DEFAULT;
	UINT offset = 0;
	if ( argc > 1 ){
		PyObject *ob = PyTuple_GET_ITEM(args, 0);
		lcid=PyLong_AsLong(ob);
		if (lcid==-1 && PyErr_Occurred()){
			PyErr_Clear();
			lcid=LOCALE_SYSTEM_DEFAULT;
			}
		else
			offset = 1;
		}

	UINT cNames = argc - offset;
	OLECHAR FAR* FAR* rgszNames = new LPOLESTR[cNames];

	for ( i = 0 ; i < cNames; ++i )
	{
		PyObject *ob = PySequence_GetItem(args, i + offset);
		if ( !ob )
		{
			for (;i>0;i--)
				PyWinObject_FreeBstr(rgszNames[i-1]);
			delete [] rgszNames;
			return NULL;
		}
		if (!PyWinObject_AsBstr(ob, rgszNames+i)) {
			for (;i>0;i--)
				PyWinObject_FreeBstr(rgszNames[i-1]);
			delete [] rgszNames;
			return NULL;
		}
		Py_DECREF(ob);
	}

	DISPID FAR* rgdispid = new DISPID[cNames];
	IDispatch *pMyDispatch = GetI(self);
	if (pMyDispatch==NULL) return NULL;
	PY_INTERFACE_PRECALL;
	HRESULT hr = pMyDispatch->GetIDsOfNames(IID_NULL, rgszNames, cNames, lcid, rgdispid);
	PY_INTERFACE_POSTCALL;

	for (i=0;i<cNames;i++)
		PyWinObject_FreeBstr(rgszNames[i]);
	delete [] rgszNames;

	if ( FAILED(hr) )
		return PyCom_BuildPyException(hr, pMyDispatch, IID_IDispatch);

	PyObject *result;

	/* if we have just one name, then return a single DISPID (int) */
	if ( cNames == 1 )
	{
		result = PyInt_FromLong(rgdispid[0]);
	}
	else
	{
		result = PyTuple_New(cNames);
		if ( result )
		{
			for ( i = 0; i < cNames; ++i )
			{
				PyObject *ob = PyInt_FromLong(rgdispid[i]);
				if ( !ob )
				{
					delete [] rgdispid;
					return NULL;
				}
				PyTuple_SET_ITEM(result, i, ob);
			}
		}
	}

	delete [] rgdispid;
	return result;
}
Ejemplo n.º 2
1
/* 
 The real invoke mechanism that handles all the details.
*/
SEXP
R_COM_Invoke(SEXP obj, SEXP methodName, SEXP args, WORD callType, WORD doReturn,
             SEXP ids)
{
 IDispatch* disp;
 SEXP ans = R_NilValue;
 int numNamedArgs = 0, *namedArgPositions = NULL, i;
 HRESULT hr;

 // callGC();
 disp = (IDispatch *) getRDCOMReference(obj);

#ifdef ANNOUNCE_COM_CALLS
 fprintf(stderr, "<COM> %s %d %p\n", CHAR(STRING_ELT(methodName, 0)), (int) callType, 
                                     disp);fflush(stderr);
#endif

 DISPID *methodIds;
 const char *pmname = CHAR(STRING_ELT(methodName, 0));
 BSTR *comNames = NULL;

 SEXP names = GET_NAMES(args);
 int numNames = Rf_length(names) + 1;

 SetErrorInfo(0L, NULL);

 methodIds = (DISPID *) S_alloc(numNames, sizeof(DISPID));
 namedArgPositions = (int*) S_alloc(numNames, sizeof(int)); // we may not use all of these, but we allocate them

 if(Rf_length(ids) == 0) {
     comNames = (BSTR*) S_alloc(numNames, sizeof(BSTR));

     comNames[0] = AsBstr(pmname);
     for(i = 0; i < Rf_length(names); i++) {
       const char *str = CHAR(STRING_ELT(names, i));
       if(str && str[0]) {
         comNames[numNamedArgs+1] = AsBstr(str);
         namedArgPositions[numNamedArgs] = i;
         numNamedArgs++;
       }
     }
     numNames = numNamedArgs + 1;

     hr = disp->GetIDsOfNames(IID_NULL, comNames, numNames, LOCALE_USER_DEFAULT, methodIds);

     if(FAILED(hr) || hr == DISP_E_UNKNOWNNAME /* || DISPID mid == DISPID_UNKNOWN */) {
       PROBLEM "Cannot locate %d name(s) %s in COM object (status = %d)", numNamedArgs, pmname, (int) hr
	 ERROR;
     }
 } else {
   for(i = 0; i < Rf_length(ids); i++) {
     methodIds[i] = (MEMBERID) NUMERIC_DATA(ids)[i];
     //XXX What about namedArgPositions here.
   }
 }


 DISPPARAMS params = {NULL, NULL, 0, 0};
 
 if(args != NULL && Rf_length(args) > 0) {

   hr = R_getCOMArgs(args, &params, methodIds, numNamedArgs, namedArgPositions);

   if(FAILED(hr)) {
     clearVariants(&params);
     freeSysStrings(comNames, numNames);
     PROBLEM "Failed in converting arguments to DCOM call"
     ERROR;
   }
   if(callType & DISPATCH_PROPERTYPUT) {
     params.rgdispidNamedArgs = (DISPID*) S_alloc(1, sizeof(DISPID));
     params.rgdispidNamedArgs[0] = DISPID_PROPERTYPUT;
     params.cNamedArgs = 1;
   }
 }

 VARIANT varResult, *res = NULL;

 if(doReturn && callType != DISPATCH_PROPERTYPUT)
   VariantInit(res = &varResult);

 EXCEPINFO exceptionInfo;
 memset(&exceptionInfo, 0, sizeof(exceptionInfo));
 unsigned int nargErr = 100;

#ifdef RDCOM_VERBOSE
 if(params.cNamedArgs) {
   errorLog("# of named arguments to %d: %d\n", (int) methodIds[0], 
                                                (int) params.cNamedArgs);
   for(int p = params.cNamedArgs; p > 0; p--)
     errorLog("%d) id %d, type %d\n", p, 
	                             (int) params.rgdispidNamedArgs[p-1],
                                     (int) V_VT(&(params.rgvarg[p-1])));
 }
#endif

 hr = disp->Invoke(methodIds[0], IID_NULL, LOCALE_USER_DEFAULT, callType, &params, res, &exceptionInfo, &nargErr);
 if(FAILED(hr)) {
   if(hr == DISP_E_MEMBERNOTFOUND) {
     errorLog("Error because member not found %d\n", nargErr);
   }

#ifdef RDCOM_VERBOSE
   errorLog("Error (%d): <in argument %d>, call type = %d, call = \n",  
	   (int) hr, (int)nargErr, (int) callType, pmname);
#endif

    clearVariants(&params);
    freeSysStrings(comNames, numNames);

    if(checkErrorInfo(disp, hr, NULL) != S_OK) {
 fprintf(stderr, "checkErrorInfo %d\n", (int) hr);fflush(stderr);
      COMError(hr);
    }
 }

 if(res) {
   ans = R_convertDCOMObjectToR(&varResult);
   VariantClear(&varResult);
 }
 clearVariants(&params);
 freeSysStrings(comNames, numNames);

#ifdef ANNOUNCE_COM_CALLS
 fprintf(stderr, "</COM>\n", (int) callType);fflush(stderr);
#endif

 return(ans);
}
Ejemplo n.º 3
0
		VARIANT ObjectInstance::Execute(const wstring methodName, DISPPARAMS inputParameters)
		{
			if (this->objectHandle == NULL)
			{
				throw new RuntimeHostException("ObjectHandle is no longer valid");
			}

			VARIANT v;
			DISPID	dispid;
			LPOLESTR szMethodName = _bstr_t(methodName.data());
			VARIANT result;
			EXCEPINFO pExcepInfo;
			unsigned int puArgErr = 0;
			
			// Initialze the variants
			VariantInit(&v);
			VariantInit(&result);
					
			HRESULT hr = this->objectHandle->Unwrap(&v);
			if (!SUCCEEDED(hr))
			{
				throw new RuntimeHostException("Unable to retrieve method information");
			}

			// The .NET Component should expose IDispatch
			IDispatch* pdispatch = v.pdispVal;				

			// Retrieve the DISPID
			hr = pdispatch->GetIDsOfNames(
								IID_NULL,
								&szMethodName,
								1,
								LOCALE_SYSTEM_DEFAULT,
								&dispid);
			if (!SUCCEEDED(hr))
			{
				throw new RuntimeHostException("Unable to retrieve method information");
			}

			// Invoke the method on the IDispatch Interface
			hr = pdispatch->Invoke(
							dispid,
							IID_NULL,
							LOCALE_SYSTEM_DEFAULT,
							DISPATCH_METHOD,
							&inputParameters,
							&result,
							&pExcepInfo,
							&puArgErr);

			if (!SUCCEEDED(hr))
			{
				throw new RuntimeHostException("Error on method execution");
			}

			return result;
		}
Ejemplo n.º 4
0
// Prints the WORD document if everything goes fine
// otherwise error is returned
int CAutoWord::PrintDocument(char *strFilePath)
{
	// Open the document
	VARIANT varRetVal;
	EXCEPINFO excepInfo; 	// this variable contains exception info if any Invoke call fails
	VARIANTARG varg;
	varg.vt = VT_BSTR;
	varg.bstrVal = _bstr_t(strFilePath); // this is the MS-word document filename, must be changed to a valid filename that exists on disk
	DISPPARAMS dpOpen = { &varg, NULL, 1, 0 };
	DISPID dispOpenID;
	LPOLESTR szOpenDoc = L"Open";
	HRESULT hr = m_pDocuments->GetIDsOfNames(IID_NULL, &szOpenDoc, 1, LOCALE_SYSTEM_DEFAULT, &dispOpenID);
	hr = m_pDocuments->Invoke(dispOpenID, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &dpOpen, &varRetVal, &excepInfo, NULL);
	if (FAILED(hr))
	{
		OutputDebugString("Error opening the document\n");
		Destroy();
		return -1;
	}
	
	IDispatch* pDocument = varRetVal.pdispVal;

	// Call PrintOut method of the opened Document 
	DISPPARAMS dpPrint = { NULL, NULL, 0, 0 };
	DISPID dispPrintID;
	LPOLESTR szPrintDoc = L"PrintOut";
	hr = pDocument->GetIDsOfNames(IID_NULL, &szPrintDoc, 1, LOCALE_SYSTEM_DEFAULT, &dispPrintID);
	hr = pDocument->Invoke(dispPrintID, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &dpPrint, &varRetVal, NULL, NULL);
	if (FAILED(hr))
	{
		OutputDebugString("The document could not be printed\n");
		Destroy();
		return -1;
	}

	// Close the document now.
	DISPPARAMS dpClose = { NULL, NULL, 0, 0 };
	DISPID dispCloseID;
	LPOLESTR szCloseDoc = L"Close";
	hr = pDocument->GetIDsOfNames(IID_NULL, &szCloseDoc, 1, LOCALE_SYSTEM_DEFAULT, &dispCloseID);
	hr = pDocument->Invoke(dispCloseID, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &dpClose, &varRetVal, &excepInfo, NULL);
	
	return 0;
}
Ejemplo n.º 5
0
HRESULT __stdcall ScriptHost::Run(WCHAR *procname, DISPPARAMS *args, VARIANT *results)
{
    assert(procname != nullptr);

    if (procname == nullptr)
        return E_POINTER;

	IDispatch *disp = nullptr;
	_activeScript->GetScriptDispatch(nullptr, &disp);
	DISPID dispid = 0;
	disp->GetIDsOfNames(IID_NULL, &procname, 1, LOCALE_SYSTEM_DEFAULT, &dispid);
	EXCEPINFO info;
	UINT argErr;
	args->rgdispidNamedArgs = &dispid;
	HRESULT hr = disp->Invoke(dispid, IID_NULL, NULL, DISPATCH_METHOD, args, results, &info, &argErr);
	return hr;
}
Ejemplo n.º 6
0
void CEasyPDFCtrl::GetURL()
{
	USES_CONVERSION;  

	IOleContainer* pContainer = NULL;
	IHTMLDocument* pDoc = NULL;
	m_pClientSite->GetContainer( &pContainer );
	if ( pContainer != NULL )
	pContainer->QueryInterface( IID_IHTMLDocument, (void**)&pDoc );

	HRESULT hresult;
	OLECHAR FAR* szMember = T2W(_T("Initilize"));

	DISPID dispid;
	DISPPARAMS dispparamsNoArgs = {NULL, NULL, 0, 0};

	IDispatch * pdisp = NULL;
	pDoc->get_Script(&pdisp);
	hresult = pdisp->GetIDsOfNames(IID_NULL,&szMember,1, LOCALE_SYSTEM_DEFAULT,&dispid);
	hresult = pdisp->Invoke(dispid,IID_NULL,LOCALE_USER_DEFAULT,DISPATCH_METHOD,&dispparamsNoArgs, NULL, NULL, NULL);
	pContainer->Release();
}
Ejemplo n.º 7
0
DISPID get_dispid( IUnknown* punk, char *propname, BOOL *bVariant )
{
	//		IDispatch の DISPID を取得する
	//
	HRESULT hr;
	IDispatch *disp;
	DISPID dispid;
	char *name = propname;
	LPOLESTR list[]={ (LPOLESTR)(hspctx->stmp) };

	if ( name[0] == '\0' ) return DISPID_VALUE;

	if ( bVariant != NULL ) *bVariant = ( name[0] == '.' );
	if ( name[0] == '.' ) name++;

	disp = (IDispatch *)punk;
	cnvwstr( hspctx->stmp, name, HSPCTX_REFSTR_MAX/sizeof(WCHAR)-1 );
	hr = disp->GetIDsOfNames( IID_NULL, list, 1, LOCALE_SYSTEM_DEFAULT, &dispid );

	if ( FAILED(hr) || dispid == DISPID_UNKNOWN ) throw HSPERR_INVALID_PARAMETER;
	return dispid;
}
Ejemplo n.º 8
0
// ScriptObject::setMultinameProperty checks if our traits have 'needsHashtable' -
// but we don't.  Its possible 'needsHashtable' is misnamed and means more like 'isDynamic'
// so we should revisit this...
void MSIDispatchConsumer::setMultinameProperty(Multiname* name, Atom value)
{
    // its possible we should just call setStringProperty(), which calls
    // setAtomProperty(), and we should add our impl there - but let's see
    // if we can get away without that for now...
    DISPID id;
    AXTam *axcore = (AXTam *)core();
    OLECHAR *olename = (OLECHAR *)name->getName()->c_str();
    IDispatch *disp = (IDispatch *)getDispatch();
    HRESULT hr = disp->GetIDsOfNames(IID_NULL, &olename, 1, 0, &id);
    // ScriptObject::setMultinameProperty just throws an exception, so
    // no point trying it...
    if (FAILED(hr))
        axcore->throwCOMConsumerError(hr);
    // Now create args for the call.
    EXCEPINFO ei;
    CComVariant arg;
    axcore->atomToVARIANT(value, &arg);
    DISPPARAMS params = {&arg, NULL, 1, 0};
    hr = disp->Invoke(id, IID_NULL, 0, DISPATCH_PROPERTYPUT, &params, NULL, &ei, NULL);
    if (FAILED(hr))
        axcore->throwCOMConsumerError(hr, &ei);
}
Ejemplo n.º 9
0
Atom MSIDispatchConsumer::callProperty(avmplus::Multiname *name, int argc, avmplus::Atom *argv)
{
    // Not sure how to best handle this re 'builtin' names, such as toString()
    // XXX - need a map of DISPIDs to speed things up, and/or optimizations
    // using the typelib.
    DISPID id;
    AXTam *axcore = (AXTam *)core();
    IDispatch *disp = (IDispatch *)getDispatch();
    OLECHAR *olename = (OLECHAR *)name->getName()->c_str();
    HRESULT hr = disp->GetIDsOfNames(IID_NULL, &olename, 1, 0, &id);
    if (hr == DISP_E_UNKNOWNNAME) {
        // not a name this object has - see if its builtin.
        return ScriptObject::callProperty(name, argc, argv);
    }
    if (FAILED(hr))
        axcore->throwCOMConsumerError(hr);
    // Now create args for the call.
    EXCEPINFO ei;
    CComVariant *pArgs = new CComVariant[argc];
    //memset(pArgs, 0, sizeof(VARIANT) * argc);
    // Take care to not early exit without cleaning up variants
    int i;
    for (i=0; i<argc; i++) {
        //VariantInit(pArgs+i);
        axcore->atomToVARIANT(argv[i+1], pArgs+i);
    }
    DISPPARAMS params = {pArgs, NULL, argc, 0};
    CComVariant ret;
    hr = disp->Invoke(id, IID_NULL, 0, DISPATCH_METHOD, &params, &ret, &ei, NULL);
    //for (i=0;i<argc;i++)
    //	VariantClear(pArg+i);
    delete [] pArgs;
    if (FAILED(hr))
        axcore->throwCOMConsumerError(hr, &ei);
    return axcore->toAtom(ret);
}
Ejemplo n.º 10
0
void LaunchWord(CString sPathWord,CString sPathOutput){

	BSTR param2 = sPathWord.AllocSysString();//SysAllocString(OLESTR("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\IEXPLORE.EXE"));
	BSTR param1 = sPathOutput.AllocSysString();//SysAllocString(OLESTR(""));
	BSTR name1 = SysAllocString(OLESTR("PathWord"));
	BSTR name2 = SysAllocString(OLESTR("PathOutput"));

	AddArgumentCString(name1,0,param1);
	AddArgumentCString(name2,0,param2);

	VARIANTARG FAR rgvarg[2];

	
	V_BSTRREF(&rgvarg[0]) = &param1;
	V_BSTRREF(&rgvarg[1]) = &param2;


	DISPPARAMS dpNoArgs = {g_aVargs, NULL, 2, 0};
	VARIANT vResult;
	OLECHAR FAR* szFunction;
	//BSTR bstrTemp;

	// IDispatch pointers for Word's objects
	//IDispatch* pDispDocs;      //Documents collection

	// DISPIDs
	DISPID dispid_Docs;        //Documents property of Application 
							   //object

	//Initialize the COM libraries
	::CoInitialize(NULL);

	// Create an instance of the Word application and obtain the 
	// pointer to the application's IDispatch interface.
	CLSID clsid;
	CLSIDFromString(L"UtilsVB.clsLauncher", &clsid);  

	IUnknown* pUnk;
	HRESULT hr = ::CoCreateInstance( clsid, NULL, CLSCTX_SERVER,
									 IID_IUnknown, (void**) &pUnk);
	IDispatch* pDispApp;
	hr = pUnk->QueryInterface(IID_IDispatch, (void**)&pDispApp);

	// Get IDispatch* for the Documents collection object
	szFunction = OLESTR("Launcher");


	hr = pDispApp->GetIDsOfNames (IID_NULL, &szFunction, 1, 
								  LOCALE_USER_DEFAULT, &dispid_Docs);

	unsigned int FAR uArgErr;
	hr = pDispApp->Invoke (dispid_Docs, IID_NULL, 
						   LOCALE_USER_DEFAULT, DISPATCH_METHOD, 
						   &dpNoArgs, &vResult, NULL, &uArgErr);
	




	//Execute Internet Explorer
	/*
	CString sPath;
	HINSTANCE hinstance=ShellExecute(
		AfxGetMainWnd( )->m_hWnd,	//HWND hwnd, 
		"open",						//LPCTSTR lpVerb,
		CString(vResult.bstrVal),//"C:\\Archivos de programa\\Internet Explorer\\IEXPLORE.EXE",//"C:\\Archivos de programa\\Microsoft Office\\Office\\WINWORD.EXE",//LPCTSTR lpFile, 
		sPath,//"\"file://C:\\2002\\DraftCable\\Src\\testfile.htm\"",				//LPCTSTR lpParameters, 
		NULL,						//LPCTSTR lpDirectory,
		SW_SHOWNORMAL				//INT nShowCmd
	);
	*/



	ClearAllArgs();
	pDispApp->Release();
	pUnk->Release();

	//...
	::CoUninitialize();

}
Ejemplo n.º 11
0
/* this is a console application */
int main ()
{
	EXCEPINFO excepinfo;
	unsigned int argerr;
	SAFEARRAY *psa;
	DISPID dispid;	
	OLECHAR *name;
	VARIANT varResult;
	VARIANTARG varg, varga[2];
	BSTR bstrIn;
	IDispatch *pIDispatch = NULL;
	int status = 0;
	HRESULT hr;

	printf("dspdisp - DADiSP IDispatch Test, Initializing...\n");

	hr = OleInitialize(NULL);
	if (FAILED(hr)) 
	{
		trace("Failed to OleInitialize");
		return(1);
	}

	// Get the CLSID for the application.
	wchar_t progid[] = L"DADiSP.Application";
	CLSID clsid;
 	hr = ::CLSIDFromProgID(progid, &clsid);
	if(FAILED(hr))
	{
		trace("Failed to CLSIDFromProgID");
		status = 1;
		goto exitpt;
	}

	// start DADiSP as an automation server
	hr = ::CoCreateInstance(clsid,
	                        NULL,
	                        CLSCTX_LOCAL_SERVER,
	                        IID_IDispatch,
	                        (void**)&pIDispatch);
	if (FAILED(hr))
	{
		trace("CoCreateInstance Failed");
		status = 1;
		goto exitpt;
	}
	trace("CoCreateInstance Succeeded.");


	// ---------------------------
	//  dadisp.getdata("version")
	// ---------------------------

	// First we need to get the ID for the function name
	ANSIToUnicode("GetData", &name);

	hr = pIDispatch->GetIDsOfNames(IID_NULL,
	                               &name,
	                               1,
	                               GetUserDefaultLCID(),
	                               &dispid);
	if (FAILED(hr))
	{
		trace("Query GetIDsOfNames Failed");
		status = 1;
		goto exitpt;
	}
	
	trace("\ndadisp.getdata(\"version\")");

	// Convert the wide-character string to a BSTR.
	CstrToBstr("version", &bstrIn);

	// Build up the parameters for the invoke call.

	// Allocate and initialize a VARIANT argument.
	::VariantInit(&varg);      // Initialize the VARIANT.
	V_VT(&varg)   = VT_BSTR;   // Type of VARIANT data
	V_BSTR(&varg) = bstrIn;    // Data for the VARIANT

	// Fill in the DISPPARAMS structure.
	DISPPARAMS param;
	param.cArgs = 1;                 // Number of arguments
	param.rgvarg = &varg;            // Arguments
	param.cNamedArgs = 0;            // Number of named args
	param.rgdispidNamedArgs = NULL;  // Named arguments

	// Allocate a variant for the returned parameter.
	::VariantInit(&varResult);

	// Invoke the function.
	hr = pIDispatch->Invoke(dispid,
	                        IID_NULL,
	                        GetUserDefaultLCID(),
	                        DISPATCH_METHOD,
	                        &param,
	                        &varResult,
	                        &excepinfo,
	                        &argerr);
	if (FAILED(hr))
	{
		trace("Invoke Failed");
		ShowException(name, hr, &excepinfo, argerr);
		status = 1;
		goto exitpt;
	}

	// Display the returned value
	DisplayVariant(&varResult);


	// ------------------------------------
	//  dadisp.getdata("max(gnorm(100,1))")
	// ------------------------------------

	::SysFreeString(bstrIn);
	CstrToBstr("max(gnorm(100,1))", &bstrIn);

	// Build up the parameters for the invoke call.

	// Allocate and initialize a VARIANT argument.
	::VariantInit(&varg);      // Initialize the VARIANT.
	V_VT(&varg)   = VT_BSTR;   // Type of VARIANT data
	V_BSTR(&varg) = bstrIn;    // Data for the VARIANT

	// Fill in the DISPPARAMS structure.
	param.cArgs = 1;                 // Number of arguments
	param.rgvarg = &varg;            // Arguments
	param.cNamedArgs = 0;            // Number of named args
	param.rgdispidNamedArgs = NULL;  // Named arguments

	// Allocate a variant for the returned parameter.
	::VariantInit(&varResult);

	trace("\ndadisp.getdata(\"max(gnorm(100,1))\")");

	// Invoke the function.
	hr = pIDispatch->Invoke(dispid,
	                        IID_NULL,
	                        GetUserDefaultLCID(),
	                        DISPATCH_METHOD,
	                        &param,
	                        &varResult,
	                        &excepinfo,
	                        &argerr);
	if (FAILED(hr))
	{
		trace("Invoke Failed");
		ShowException(name, hr, &excepinfo, argerr);
		status = 1;
		goto exitpt;
	}

	// Display the returned value
	DisplayVariant(&varResult);



	// -------------------------------------
	//  dadisp.putdata("MyVar", RandomArray)
	// -------------------------------------

	free(name);
	ANSIToUnicode("Putdata", &name);

	hr = pIDispatch->GetIDsOfNames(IID_NULL,
	                               &name,
	                               1,
	                               GetUserDefaultLCID(),
	                               &dispid);
	if (FAILED(hr))
	{
		trace("Query GetIDsOfNames Failed");
		status = 1;
		goto exitpt;
	}

	// create a random array
	CreateRandomArray(darray, ARRAY_SIZE);

	// convert to automation SafeArray
	psa = DarrayToSafeArray(darray, ARRAY_SIZE, 1);

	::SysFreeString(bstrIn);
	CstrToBstr("MyVar", &bstrIn);

	// Allocate and initialize a VARIANT argument.
	// This routine has two arguments, must add in *reverse* order

	::VariantInit(&varga[1]);        // Initialize the VARIANT.
	V_VT(&(varga[1]))   = VT_BSTR;   // DADiSP variable name
	V_BSTR(&(varga[1])) = bstrIn;    // Data for the VARIANT

	::VariantInit(&varga[0]);              // Initialize the VARIANT.
	V_VT(&(varga[0]))    = VT_ARRAY|VT_R8; // Array of doubles
	V_ARRAY(&(varga[0])) = psa;            // Data for the VARIANT


	// Fill in the DISPPARAMS structure.
	param.cArgs = 2;                 // Number of arguments
	param.rgvarg = varga;            // Arguments
	param.cNamedArgs = 0;            // Number of named args
	param.rgdispidNamedArgs = NULL;  // Named arguments

	// Allocate a variant for the returned parameter.
	::VariantInit(&varResult);

	// Invoke the function.
	hr = pIDispatch->Invoke(dispid,
	                        IID_NULL,
	                        GetUserDefaultLCID(),
	                        DISPATCH_METHOD,
	                        &param,
	                        &varResult,
	                        &excepinfo,
	                        &argerr);
	if (FAILED(hr))
	{
		trace("Invoke Failed");
		ShowException(name, hr, &excepinfo, argerr);
		status = 1;
		goto exitpt;
	}

	// Display the input array
	trace("\nRandom Input Array:");

	DisplayVariant(&varga[0]);


	// ---------------------------------
	//  dadisp.getdata("fft(MyVar)")
	// ---------------------------------

	free(name);
	ANSIToUnicode("Getdata", &name);

	hr = pIDispatch->GetIDsOfNames(IID_NULL,
	                               &name,
	                               1,
	                               GetUserDefaultLCID(),
	                               &dispid);
	if (FAILED(hr))
	{
		trace("Query GetIDsOfNames Failed");
		status = 1;
		goto exitpt;
	}

	::SysFreeString(bstrIn);
	CstrToBstr("fft(MyVar)", &bstrIn);

	// Allocate and initialize a VARIANT argument.
	::VariantInit(&varg);      // Initialize the VARIANT.
	V_VT(&varg)   = VT_BSTR;   // Type of VARIANT data
	V_BSTR(&varg) = bstrIn;    // Data for the VARIANT


	// Fill in the DISPPARAMS structure.
	param.cArgs = 1;                 // Number of arguments
	param.rgvarg = &varg;            // Arguments
	param.cNamedArgs = 0;            // Number of named args
	param.rgdispidNamedArgs = NULL;  // Named arguments

	// Allocate a variant for the returned parameter.
	::VariantInit(&varResult);

	// Invoke the function.
	hr = pIDispatch->Invoke(dispid,
	                        IID_NULL,
	                        GetUserDefaultLCID(),
	                        DISPATCH_METHOD,
	                        &param,
	                        &varResult,
	                        &excepinfo,
	                        &argerr);
	if (FAILED(hr))
	{
		trace("Invoke Failed");
		ShowException(name, hr, &excepinfo, argerr);
		status = 1;
		goto exitpt;
	}

	// Display the returned array
	trace("\nFFT Output Array:");
	DisplayVariant(&varResult);

exitpt:

	// Release the dispatch interface.
	if (pIDispatch) pIDispatch->Release();

	// Uninitialize the OLE library.
	OleUninitialize();
	return(0);
}
void CDownloads_Opinions_WBEvents::OnDocumentComplete(LPDISPATCH pdWB, VARIANT *URL)
{
	IWebBrowser2Ptr spWB (pdWB);
	if (spWB == NULL)
		return;

	IDispatchPtr spdDoc;
	spWB->get_Document (&spdDoc);
	IHTMLDocumentPtr spDoc (spdDoc);
	if (spDoc == NULL)
		return;

	ICustomDocPtr spCD (spDoc); 
	if (spCD != NULL)
		spCD->SetUIHandler (&m_wbUIHandler);

	bool bSetTab = false;
	if (m_pwndOpinions->m_cSetAsCurrentTabAfterLoadComplete)
	{
		InterlockedDecrement (&m_pwndOpinions->m_cSetAsCurrentTabAfterLoadComplete);
		bSetTab = true;
	}

	if (m_pwndOpinions->m_dld == NULL)
		return;

	if (bSetTab)
		_pwndDownloads->m_wndDownloads.m_info.set_CurTab (DIT_OPINIONS);

	

	IDispatch *pdScript;
	spDoc->get_Script (&pdScript);
	if (pdScript == NULL)
		return;

	

	DISPID didFun;
	OLECHAR* pwszFunName = L"processform";

	HRESULT hr;
	hr = pdScript->GetIDsOfNames (IID_NULL, &pwszFunName, 1, LOCALE_SYSTEM_DEFAULT, &didFun);
	if (FAILED (hr))
		return;	
	
	COleVariant vtResult;
	BYTE params [] = {VTS_BSTR VTS_BSTR VTS_BSTR VTS_BSTR VTS_BSTR};

	
	

	CString strVersion;
	CMainFrame* pFrm = (CMainFrame*)AfxGetApp ()->m_pMainWnd;
	strVersion.Format ("%s_%d", vmsFdmAppMgr::getBuildNumberAsString (), pFrm->m_Customizations.get_AffiliateID ());

	CString strState;
	if (m_pwndOpinions->m_dld->pMgr->IsDone ())
		strState = "Downloaded";
	else if (m_pwndOpinions->m_dld->pMgr->IsRunning ())
		strState = "Downloading";
	else
		strState = "Paused";
	CString strSize;
	UINT64 u = m_pwndOpinions->m_dld->pMgr->GetSSFileSize ();
	if (u != _UI64_MAX) {
		char sz [100];
		_i64toa ((__int64)u, sz, 10);
		strSize = sz;
	}
	else
		strSize = "Unknown";
	CString strComment = m_pwndOpinions->m_dld->strComment;
	strComment.Replace ("\r\n", " ");
	strComment.Replace ("\r", " ");
	strComment.Replace ("\n", " ");

	

	CString strUrl;
	if (m_pwndOpinions->m_dld->pMgr->IsBittorrent ())
		strUrl = m_pwndOpinions->m_dld->pMgr->GetBtDownloadMgr ()->get_InfoHash ();
	else
		strUrl = m_pwndOpinions->m_dld->pMgr->get_URL ();

	COleDispatchDriver ddr (pdScript);
	ddr.InvokeHelper (didFun, DISPATCH_METHOD, VT_VARIANT, (void*)&vtResult,
		params, strVersion, strUrl, strComment, 
		strState, strSize); 

	
	
	
	
	RetrieveLinkToUsText (spdDoc);
}
Ejemplo n.º 13
0
void comauto::CommonLanguageRuntime::call( tagVARIANT* res, const std::wstring& assembly_, const std::wstring& class_, const std::wstring& method_, unsigned int argc, const tagVARIANT* argv, unsigned int lcid) const
{
	struct Local
	{
		Local() {::memset( this, 0, sizeof( *this)); varResult.vt = VT_EMPTY;}
		~Local()
		{
			if (spType) spType->Release();
			if (spAssembly) spAssembly->Release();
			if (spDefaultAppDomain) spDefaultAppDomain->Release();
		}
		EXCEPINFO excepInfo;
		VARIANT varResult; 
		DISPPARAMS dispParams;
		IUnknownPtr spAppDomainThunk;
		_AppDomainPtr spDefaultAppDomain; 
		_AssemblyPtr spAssembly; 
		_TypePtr spType;

		void getReturnVal( VARIANT* res)
		{
			std::memcpy( res, &varResult, sizeof(varResult));
			varResult.vt = VT_EMPTY;
			return;
		}
	};
	Local local;

	// The identifiers of the method in the .NET class to invoke:
	bstr_t bstrAssemblyName( assembly_.c_str()); 
	bstr_t bstrClassName( class_.c_str()); 
	bstr_t bstrMethodName( method_.c_str()); 
 
	WRAP( m_impl->m_runtimehost->GetDefaultDomain( &local.spAppDomainThunk));
	WRAP( local.spAppDomainThunk->QueryInterface( IID_PPV_ARGS( &local.spDefaultAppDomain)));
	WRAP( local.spDefaultAppDomain->Load_2( bstrAssemblyName, &local.spAssembly));
	WRAP( local.spAssembly->GetType_2( bstrClassName, &local.spType));

	// Create an instance of the object to invoke the method:
	variant_t vtObject;
	WRAP( local.spAssembly->CreateInstance( bstrClassName, &vtObject));
	if (!vtObject.punkVal)
	{
		throw std::runtime_error( std::string( "class definition not found '") + utf8string( bstrClassName.GetBSTR()) + "'");
	}

	// Initialize the method arguments structure:
	local.dispParams.cNamedArgs = 0;
	local.dispParams.cArgs = argc;
	local.dispParams.rgvarg = const_cast<VARIANT*>(argv);

	// Get the method invoker interface (IDispatch):
	IDispatch* dispatch = NULL;
	WRAP( vtObject.punkVal->QueryInterface( IID_IDispatch, (void**)&dispatch));

	// Get the method handle:
	DISPID gDispId = 0;
	LPOLESTR bstrMethodName_ = bstrMethodName;
	WRAP( dispatch->GetIDsOfNames( IID_NULL, &bstrMethodName_, 1, lcid, &gDispId));

	// Call that method:
	UINT puArgErr;
	HRESULT hr = dispatch->Invoke( gDispId, IID_NULL, lcid, DISPATCH_METHOD, &local.dispParams, &local.varResult, &local.excepInfo, &puArgErr);
	if (hr != S_OK)
	{
		std::string methodname = comauto::utf8string(class_) + "." + comauto::utf8string(method_);
		if (hr == DISP_E_EXCEPTION)
		{
			throw std::runtime_error( std::string("Error calling ") + methodname + " " + comauto::tostring( local.excepInfo));
		}
		else
		{
			_com_error error(hr);
			std::ostringstream errcode; 
			errcode << std::hex << " [0x" << hr << "]";
			throw std::runtime_error( std::string("Error calling ") + methodname + ": '" + comauto::utf8string(error.ErrorMessage()) + errcode.str());
		}
	}
	local.getReturnVal( res);
}
Ejemplo n.º 14
0
int DisplayDialogs(HWND hWnd, int nDialog)
{
	// Let's make a little bit COM
	HRESULT hr;
	IUnknown *pUnknown;
	CLSID ClsID;

	hr = CLSIDFromProgID(OLESTR("VPinMAME.Controller"), &ClsID);
	if ( FAILED(hr) ) {
		DisplayError(hWnd, hr, "Class couldn't be found. Maybe it isn't registered");
		return 0;
	}

	hr = CoCreateInstance(ClsID, NULL, CLSCTX_INPROC_SERVER, IID_IUnknown, (void**) &pUnknown);
	if ( FAILED(hr) ) {
		DisplayError(hWnd, hr, "Can't create the Controller class! \nPlease check that you have installed Visual PinMAME properly!");
		return 0;
	}

	// Don't want to include the header files for the class, so let's using IDispatch
	IDispatch *pDispatch;
	
	hr = pUnknown->QueryInterface(IID_IDispatch, (void**) &pDispatch);
	if ( FAILED(hr) ) {
		DisplayError(hWnd, hr, "Can't get the dispatch interface");
		pUnknown->Release();
		return 0;
	}

	OLECHAR *pszName[3] = {L"ShowPathesDialog", L"ShowOptsDialog", L"ShowAboutDialog"};
	DISPID dispid;

	hr = pDispatch->GetIDsOfNames(IID_NULL, &pszName[nDialog], 1, LOCALE_SYSTEM_DEFAULT, &dispid);
	if ( FAILED(hr) ) {
		DisplayError(hWnd, hr, "Can't get the dispatch interface");
		pDispatch->Release();
		pUnknown->Release();
		return 0;
	}
	
	VARIANT varParam;
	varParam.vt   = VT_I4;
	varParam.lVal = (long) hWnd;

	DISPPARAMS DispParams = {&varParam,NULL,1,0};
	EXCEPINFO ExcepInfo;
	hr = pDispatch->Invoke(dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &DispParams, NULL, &ExcepInfo, NULL);

	if ( FAILED(hr) ) {
		if ( hr==DISP_E_EXCEPTION )
			// actually we call the ONLY UNICODE function in Windows 9x
			MessageBoxW(0, ExcepInfo.bstrDescription, L"Error from the VPinMAME.Controller interface", MB_ICONERROR|MB_OK);
		else 
			DisplayError(hWnd, hr, "Can't get the dispatch interface");

		pDispatch->Release();
		pUnknown->Release();
		return 0;
	}

	pDispatch->Release();
	pUnknown->Release();

	return 1;
}
Ejemplo n.º 15
0
void indri::parse::WordDocumentExtractor::open( const std::string& filename ) {
  // open the document
  initialize();
  HRESULT hr;
  VARIANT result;
  DISPPARAMS parameters;
  VARIANT fileNameParameter;
  int location = filename.find_last_of("\\/");
  if(filename[location+1]=='~'){
    //skip temp-Word files
    LEMUR_THROW( LEMUR_RUNTIME_ERROR, "Skipping temp Word Files starting with ~, they cause trouble parsing. " + filename + "." );
  }

  _documentPath = filename;

  WCHAR widePathCopy[ MAX_PATH ];
  ::MultiByteToWideChar( CP_UTF8, 0, filename.c_str(), filename.length()+1, widePathCopy, MAX_PATH );

  fileNameParameter.vt = VT_BSTR;
  fileNameParameter.bstrVal = ::SysAllocString( widePathCopy );

  parameters.cArgs = 1;
  parameters.cNamedArgs = 0;
  parameters.rgdispidNamedArgs = NULL;
  parameters.rgvarg = &fileNameParameter; 

  hr = v_internal->_documentsDispatch->Invoke( v_internal->_openDispatchID,
                                               IID_NULL,
                                               LOCALE_SYSTEM_DEFAULT,
                                               DISPATCH_METHOD,
                                               &parameters,
                                               &result,
                                               NULL,
                                               NULL );
  
  if( FAILED(hr) ) {
    _officeHelper.AutoWrap(DISPATCH_METHOD, NULL,v_internal->_wordDispatch, L"Quit", 0);
    v_internal->_wordDispatch->Release();
    LEMUR_THROW( LEMUR_RUNTIME_ERROR, "Couldn't open file " + filename + "." );
  }

  IDispatch* documentDispatch = result.pdispVal;



  // get content dispatch ID
  DISPID contentDispatchID;
  LPOLESTR contentPropertyName = L"Content";

  hr = documentDispatch->GetIDsOfNames( IID_NULL,
                                        &contentPropertyName,
                                        1,
                                        LOCALE_SYSTEM_DEFAULT,
                                        &contentDispatchID );

  if( FAILED(hr) ) {
    closeWord(documentDispatch,true);
    LEMUR_THROW( LEMUR_RUNTIME_ERROR, "Couldn't get ID of \"Content\" for file " + filename + "." );
  }


  // fetch the content property
  DISPPARAMS noParameters = { NULL, NULL, 0, 0 };

  hr = documentDispatch->Invoke( contentDispatchID,
                                 IID_NULL,
                                 LOCALE_SYSTEM_DEFAULT,
                                 DISPATCH_PROPERTYGET,
                                 &noParameters,
                                 &result,
                                 NULL,
                                 NULL );

  if( FAILED(hr) ) {
    closeWord(documentDispatch,true);
    LEMUR_THROW( LEMUR_RUNTIME_ERROR, "Couldn't get content for file " + filename + "." );
  }

  IDispatch* contentDispatch = result.pdispVal;

  // get the Text property dispatch ID
  DISPID textDispatchID;
  LPOLESTR textPropertyName = L"Text";

  hr = contentDispatch->GetIDsOfNames( IID_NULL,
                                       &textPropertyName,
                                       1,
                                       LOCALE_SYSTEM_DEFAULT,
                                       &textDispatchID );

  if( FAILED(hr) ) {
    closeWord(documentDispatch,true);
    LEMUR_THROW( LEMUR_RUNTIME_ERROR, "Couldn't get text for file " + filename + "." );
  }

  // call the text method on the content
  hr = contentDispatch->Invoke( textDispatchID,
                                IID_NULL,
                                LOCALE_SYSTEM_DEFAULT,
                                DISPATCH_PROPERTYGET,
                                &noParameters,
                                &result,
                                NULL,
                                NULL );

  if( FAILED(hr) ) {
    closeWord(documentDispatch,true);
    LEMUR_THROW( LEMUR_RUNTIME_ERROR, "Couldn't get text for file " + filename + "." );
  }

  // get the document text as a string
  BSTR textResult = result.bstrVal;
  UINT textLength = ((UINT*)textResult)[-1];

  // multibyte could potentially have 3 bytes for every 1 double-byte char
  UINT convertedLength = 3*textLength;
  _documentTextBuffer.clear();

  _unparsedDocument.metadata.clear();
  _officeHelper.SetOfficeMetaData(documentDispatch,&_unparsedDocument);
  _officeHelper.writeHeaderToBuffer(_documentTextBuffer);


  

  //add to buffer
 
  
  //wordHeader


  // convert the document text into a multibyte representation
  int trueLength = ::WideCharToMultiByte( CP_UTF8, 0, textResult, -1,
                                          _documentTextBuffer.write( convertedLength ), convertedLength,
                                          NULL, NULL );
  _documentTextBuffer.unwrite( convertedLength-trueLength );

  indri::parse::MetadataPair pair;



  pair.key = "docno";
  pair.value = _documentPath.c_str();
  pair.valueLength = _documentPath.length()+1;
  _unparsedDocument.metadata.push_back( pair );

  pair.key = "path";
  pair.value = _documentPath.c_str();
  pair.valueLength = _documentPath.length()+1;
  _unparsedDocument.metadata.push_back( pair );

  pair.key = "filetype";
  pair.value = (void*) "MSWORD";
  pair.valueLength = 7;
  _unparsedDocument.metadata.push_back( pair );




  _unparsedDocument.text = _documentTextBuffer.front();
  _unparsedDocument.textLength = _documentTextBuffer.position();
  _unparsedDocument.content = _documentTextBuffer.front();
  _unparsedDocument.contentLength = _documentTextBuffer.position() - 1;

  // do something with this string here
  ::SysFreeString( textResult );
  ::SysFreeString( fileNameParameter.bstrVal );

  contentDispatch->Release();
  
  closeWord(documentDispatch,true);

  documentDispatch->Release();
  v_internal->_wordDispatch->Release();
  v_internal->_wordUnknown->Release();
  _documentWaiting = true;
}
Ejemplo n.º 16
0
    VARIANT ExecuteScript(IWebBrowser2 *pWebBrowser, const SStringW & fun,SArray<SStringW> & params)
    {
        VARIANT varErr;
        VariantInit( &varErr );

        //get document dispatch interface
        IDispatch* pDisp = NULL;

        HRESULT hr = pWebBrowser->get_Document( &pDisp );

        if ( FAILED( hr ) || pDisp == NULL )
        {
            return varErr;
        }

        IHTMLDocument2* pDoc = NULL;
        pDisp->QueryInterface( IID_IHTMLDocument2,(void**)&pDoc );
        pDisp->Release();

        IDispatch* pScript = NULL;
        hr = pDoc->get_Script( &pScript );
        pDoc->Release();

        if ( FAILED( hr ) || pScript == NULL )
        {
            return varErr;
        }

        sbstr bstrMember((int)fun.GetLength(),fun );
        DISPID dispid = 0;
        BSTR bstr = (BSTR)bstrMember;
        hr = pScript->GetIDsOfNames( IID_NULL,&(bstr),1,LOCALE_SYSTEM_DEFAULT,&dispid );

        if ( FAILED( hr ) )
        {
            return varErr;
        }

        DISPPARAMS dispparams;
        ::ZeroMemory( &dispparams,sizeof( DISPPARAMS ) );
        dispparams.cArgs = (UINT)params.GetCount();
        dispparams.rgvarg = new VARIANT[dispparams.cArgs];
        dispparams.cNamedArgs = 0;

        for ( size_t i = 0;i < params.GetCount();i++ )
        {
            size_t indx = params.GetCount() - i - 1;
            sbstr bstrParam((int)params[indx].GetLength(),params[indx]);
            dispparams.rgvarg[i].bstrVal = bstrParam.Release();
            dispparams.rgvarg[i].vt = VT_BSTR;
        }

        EXCEPINFO excepinfo;
        ::ZeroMemory( &excepinfo,sizeof( EXCEPINFO ) );
        VARIANT varRet;
        UINT nArgErr = (UINT)-1;	//initialize to invalid arg

        hr = pScript->Invoke( dispid,IID_NULL,0,DISPATCH_METHOD,&dispparams,&varRet,&excepinfo,&nArgErr );

        delete []dispparams.rgvarg;
        pScript->Release();

        if ( FAILED( hr ) )
        {
            return varErr;
        }

        return varRet;
    }
Ejemplo n.º 17
0
// thanks to Eugene Khodakovsky (I've just modified his code to make more lazy script call)
BOOL CHtmlViewer::ExecScript(TCHAR* ScriptContent,VARIANT* pScriptResult,EXCEPINFO* pExcepInfo)
{
    HRESULT hr = S_OK;

    IDispatch* pHtmlDocDispatch = NULL;
    IHTMLDocument2* pHtmlDoc = NULL;
    DISPID dispid = NULL;
    BSTR bstrMember;
    IDispatch* spScript;

    if (IsBadWritePtr(pExcepInfo,sizeof(EXCEPINFO)))
        return FALSE;

    memset(pExcepInfo, 0, sizeof(EXCEPINFO));
    pScriptResult->vt=VT_EMPTY;

    // Retrieve the document object.

    hr = pIWebBrowser->get_Document(&pHtmlDocDispatch);
    if (SUCCEEDED (hr) && (pHtmlDocDispatch != NULL))
    {
        hr = pHtmlDocDispatch->QueryInterface(IID_IHTMLDocument2,(void**)&pHtmlDoc);
        if (SUCCEEDED (hr) && (pHtmlDoc != NULL))
        {
            //Getting IDispatch for Java Script objects
            hr = pHtmlDoc->get_Script(&spScript);

            if (SUCCEEDED (hr) && (spScript != NULL))
            {
                bstrMember=SysAllocString(L"eval");// THE trick is here
                if (bstrMember)
                {
                    hr = spScript->GetIDsOfNames(IID_NULL,&bstrMember,1,LOCALE_SYSTEM_DEFAULT,&dispid);

                    if (SUCCEEDED (hr))
                    {
                        //Putting parameters
                        DISPPARAMS dispparams;
                        memset(&dispparams, 0, sizeof (DISPPARAMS));
                        dispparams.cArgs      = 1;
                        dispparams.rgvarg     = new VARIANT[dispparams.cArgs];
                        dispparams.cNamedArgs = 0;

                        dispparams.rgvarg[0].vt = VT_BSTR;

                        WCHAR* wScriptContent;
#if (defined(UNICODE)||defined(_UNICODE))
                        wScriptContent=ScriptContent;
#else
                        CAnsiUnicodeConvert::AnsiToUnicode(ScriptContent,&wScriptContent);
#endif
                        dispparams.rgvarg[0].bstrVal = SysAllocString(wScriptContent);

#if ((!defined(UNICODE))&& (!defined(_UNICODE)))
                        free(wScriptContent);
#endif
                        /*
                        // code for those who want to do the same thing
                        // using an array of string "const CStringArray& paramArray" as parameter
                        // instead of eval tips
                        
                        const int arraySize = paramArray.GetSize();
                        //Putting parameters
                        DISPPARAMS dispparams;
                        memset(&dispparams, 0, sizeof dispparams);
                        dispparams.cArgs      = arraySize;
                        dispparams.rgvarg     = new VARIANT[dispparams.cArgs];
                        dispparams.cNamedArgs = 0;

                        for( int i = 0; i < arraySize; i++)
                        {
                            CComBSTR> bstr = paramArray.GetAt(arraySize - 1 - i);
                            // back reading
                            bstr.CopyTo(&dispparams.rgvarg[i].bstrVal);
                            dispparams.rgvarg[i].vt = VT_BSTR;
                        }
                        */

                        if (dispparams.rgvarg[0].bstrVal)
                        {
                            UINT nArgErr = (UINT)-1;// initialize to invalid arg
                            //Call JavaScript function
                            hr = spScript->Invoke(dispid,
                                                    IID_NULL,
                                                    0,
                                                    DISPATCH_METHOD,
                                                    &dispparams,
                                                    pScriptResult,
                                                    pExcepInfo,
                                                    &nArgErr);

                            SysFreeString(dispparams.rgvarg[0].bstrVal);
                        }

                        delete [] dispparams.rgvarg;
                    }

                    SysFreeString(bstrMember);
                }
                
            }
            pHtmlDoc->Release();
        }
        pHtmlDocDispatch->Release();
    }

    return SUCCEEDED (hr);
}
Ejemplo n.º 18
0
int _tmain(int argc, _TCHAR* argv[])
{
    HRESULT hr;             // COM 戻り値用変数
    IClassTest* pClassTest; // COMインターフェイスポインタ

    // COMの初期化 ◆◆追加
	hr = ::CoInitialize(NULL);
    if(FAILED(hr)){
        printf("CoInitialize 失敗\n");
        return 0;
    }

	// ----------------------------------------------------------------------------------------------------
	// ----------------------------------------------------------------------------------------------------

	// <以下のコードは、アーリーバインディング方式での呼び出し>

	// インスタンスの作成(CLSID:[CLSID_ClassTest]とIID:[IID_IClassTest]を指定して、ポインタを取得)
    hr = ::CoCreateInstance((REFCLSID) CLSID_ClassTest, 0, CLSCTX_INPROC_SERVER,
							(REFIID) IID_IClassTest, (LPVOID*)&pClassTest);

    if(FAILED(hr)){
        printf("CoCreateInstance 失敗\n");
        return 0;
    }

	// BSTRを処理する場合は、_bstr_tが楽(解放など)
	// http://mzs184.blogspot.com/2008/04/bstrbstrt.html

	// _bstr_t Class
	// http://msdn.microsoft.com/ja-jp/library/zthfhkd6.aspx
	// _bstr_t::operator =
	// http://msdn.microsoft.com/ja-jp/library/7bh2f8sk.aspx
	_bstr_t bstrText =  L"だいすけ";
	_bstr_t bstrCaption = L"にしの";
	_bstr_t bstrRetVal;

	// メソッド呼び出し

	// _bstr_t::wchar_t*, _bstr_t::char*
	// BSTRはOLECHAR(= WCHAR)のポインタなので適用可能。
	// http://msdn.microsoft.com/ja-jp/library/btdzb8eb.aspx
	// _bstr_t::GetAddress
	// http://msdn.microsoft.com/ja-jp/library/t2x13207.aspx
	hr = pClassTest->MethodTest(bstrText, bstrCaption, bstrRetVal.GetAddress());

	if(FAILED(hr)){
        printf("MethodTest 失敗\n");
        return 0;
    }

	MessageBox(NULL, bstrRetVal, L"戻り値", MB_OK);

	// bstrRetValをクリア(DetachしてSysFreeString)

	// _bstr_t::Detach
    // http://msdn.microsoft.com/en-us/library/3c73x1sf.aspx
	// SysFreeString
	// http://msdn.microsoft.com/ja-jp/site/ms221481

	BSTR bstr = bstrRetVal.Detach();

	if(bstr != NULL)
	{
		SysFreeString(bstr);
	}

	// bstrCaptionの再設定
	bstrCaption = L"";

	// メソッド呼び出し(同上)
	hr = pClassTest->MethodTest(bstrText, bstrCaption, bstrRetVal.GetAddress());
	
	// Dr.GUI Online
	// Dr.GUI と COM オートメーション、
	// 第 3 部:続 COM のすばらしきデータ型
	// http://msdn.microsoft.com/ja-jp/library/cc482694.aspx
	// ISupportErrorInfo、IErrorInfoでエラー情報を取得

	if(FAILED(hr))
	{
		// IID_ISupportErrorInfoインターフェイスを取得
		ISupportErrorInfo *pSupport;
		hr = pClassTest->QueryInterface(IID_ISupportErrorInfo, (void**)&pSupport);

		if (SUCCEEDED(hr)) {

			hr = pSupport->InterfaceSupportsErrorInfo(IID_IClassTest);

			if (hr == S_OK) { // can't use SUCCEEDED here! S_FALSE succeeds!

				IErrorInfo *pErrorInfo;
				hr = GetErrorInfo(0, &pErrorInfo);

				if (SUCCEEDED(hr)) {
					// FINALLY can call methods on pErrorInfo! ...and handle the error!

					_bstr_t bstrErrorDescription;
					pErrorInfo->GetDescription(bstrErrorDescription.GetAddress());

					// エラー情報
					MessageBox(NULL, bstrErrorDescription, L"ErrorDescription", MB_OK);

					// don't forget to release!
					pErrorInfo->Release();
				}
			}

			// don't forget to release!
			pSupport->Release();
		}
	}

	// don't forget to release!
	pClassTest->Release();

	// ----------------------------------------------------------------------------------------------------
	// ----------------------------------------------------------------------------------------------------

	// <以下のコードは、レイトバインディング方式での呼び出し>

	// CLSID の取得
    CLSID clsid;
    hr = CLSIDFromProgID(L"VC_COM.ClassTest", &clsid);

    if(FAILED(hr)){
        printf("CLSIDFromProgID 失敗\n");
        return 0;
    }

	// インスタンスの作成(CLSIDとIID:[IID_IDispatch]を指定して、ポインタを取得)
    IDispatch* pDisp = NULL;
    hr = ::CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IDispatch, (void**)&pDisp);

    if(FAILED(hr)){
        printf("CoCreateInstance 失敗\n");
        return 0;
    }
	
	// COMディスパッチ識別子の取得
	DISPID dispID;
	OLECHAR* wszName = L"MethodTest";
	hr = pDisp->GetIDsOfNames(IID_NULL, &wszName, 1, LOCALE_USER_DEFAULT, &dispID);

	if(FAILED(hr)){
        printf("GetIDsOfNames 失敗\n");
        exit(1);
    }
	
	// CComVariant クラス(CComVariant は VARIANT 型から派生)
	// http://msdn.microsoft.com/ja-jp/library/ac97df2h.aspx

	// 引数を VARIANT 配列に設定
    CComVariant pvArgs[2];
	pvArgs[0] = L"だいすけ";
	pvArgs[1] = L"にしの";

	// 戻り値を VARIANT変数
	CComVariant pvResult;

	// DISPPARAMS の設定
    DISPPARAMS dispParams;

    dispParams.rgvarg = pvArgs;
    dispParams.rgdispidNamedArgs = NULL;
    dispParams.cArgs = 2;
    dispParams.cNamedArgs = 0;

	// メソッドにレイトバインド(Invoke)
	hr = pDisp->Invoke(dispID, IID_NULL,
		LOCALE_USER_DEFAULT, DISPATCH_METHOD,
		&dispParams, &pvResult, NULL, NULL);

	if(FAILED(hr)){
        printf("MethodTest 失敗\n");
        return 0;
    }

	// BSTRで格納されている時、tagVARIANTのメンバ、bstrValで取得可能。
	// BSTRはOLECHAR(= WCHAR)のポインタなのでLPWSTRにキャスト可能。
	MessageBox(NULL, (LPWSTR)pvResult.bstrVal, L"戻り値", MB_OK);

	// don't forget to release!
	pDisp->Release();

	// ----------------------------------------------------------------------------------------------------
	// ----------------------------------------------------------------------------------------------------

    // COMの終了処理 ◆◆追加
    ::CoUninitialize();

    return 0;
}
Ejemplo n.º 19
0
void CDesertConfigDialog::OnBnClickedCyPhy2MorphMatrix()
{
	set<int> ids;
	int cnt = m_cfglist.GetItemCount();
	for(int i=0; i<cnt; ++i)
	{
		if(m_cfglist.GetCheck(i)) {
			ids.insert(m_cfglist.GetItemID(i));
		}
	}
	dhelper_ptr->exportModel_ForMorphMatrix(ids);

	IDispatch *exceldispatch = NULL;

	try {

		// CXLAutomation XL;
		// XL.OpenExcelFile(mmFileDlg.m_filepath);

		//CCyPhy2MorphMatrixFileDlg mmFileDlg;
		
		//if(mmFileDlg.DoModal()==IDOK)
		//{
			::CoInitialize(NULL);

			if( exceldispatch == NULL)
			{
				CLSID clsid;
				CLSIDFromProgID(L"Excel.Application", &clsid);

				HRESULT hRes = CoCreateInstance(clsid, NULL, CLSCTX_LOCAL_SERVER, 
								   IID_IDispatch, (void**)&exceldispatch);
				if(FAILED(hRes))
				{
					MessageBox(_T("Failed to create Excel Application Object"));
					return;
				}

				DISPID dispidVisible;
				OLECHAR *propertyName = L"Visible";
				hRes = exceldispatch->GetIDsOfNames(IID_NULL, &propertyName, 1, LOCALE_SYSTEM_DEFAULT, &dispidVisible);
         
				if(FAILED(hRes))
				{
					MessageBox(_T("Failed to access Excel Application Methods"));
					return;
				}
         
				unsigned returnArg;
				VARIANT varTrue;
				DISPID rgDispidNamedArgs[1];
				rgDispidNamedArgs[0] = DISPID_PROPERTYPUT;
				DISPPARAMS params = { &varTrue, rgDispidNamedArgs, 1, 1 };

				varTrue.vt = VT_BOOL;
				varTrue.boolVal = VARIANT_TRUE;
         
				hRes = exceldispatch->Invoke(dispidVisible, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYPUT, &params, 0, 0, &returnArg);
         
				if(FAILED(hRes))
				{
					MessageBox(_T("Failed to access Excel Application Methods"));
					exceldispatch->Release();
					return;
				}

 			}
		//}
	} catch (...) {
		// TODO: Show error dialog
		exceldispatch->Release();
	}
}
Ejemplo n.º 20
0
int _tmain(int argc, _TCHAR* argv[])
{
	HRESULT  hr;

    // Initialize COM.
    CoInitialize(NULL);

	LPCOLESTR progID = OLESTR("jniwrapper.comtojavasample");
	LPCLSID clsID = new CLSID();
	CLSIDFromProgID(progID, clsID);

	//Working with Java COM Server via the IPersist interface
	IPersist* iPersistInst;
	hr = CoCreateInstance(*clsID,
                           NULL,
                           CLSCTX_LOCAL_SERVER,
						   IID_IPersist,
                           (void **)&iPersistInst);

	if (SUCCEEDED(hr))
		printf("The instance of IPersist interface was succesfully created.\n");
	else 
		printf("Error while trying to create the instance of the IPersist interface.\n");

	CLSID resultClsID;
	iPersistInst->GetClassID(&resultClsID);
	LPOLESTR stringClsID;
	StringFromCLSID(resultClsID , &stringClsID);
	wprintf(L"GetClassID = %s%s", (wchar_t*)stringClsID, "\n");

	//Working with Java COM Server via the IDispatch interface
	IDispatch* iDispatchInst;
	hr = CoCreateInstance(*clsID,
                           NULL,
                           CLSCTX_LOCAL_SERVER,
						   IID_IDispatch,
                           (void **)&iDispatchInst);
	if (SUCCEEDED(hr))
		printf("The instance of IDispatch interface was succesfully created.\n");
	else 
		printf("Error while trying to create the instance of the IDispatch interface.\n");

	DISPID dispid;
	VARIANT result;
	OLECHAR* methodName;
	DISPPARAMS dispparamsNoArgs = {NULL, NULL, 0, 0};

	//Calling the "add" method
	methodName = L"add";
	iDispatchInst->GetIDsOfNames(IID_NULL, &methodName, 1, GetUserDefaultLCID(), &dispid);
	
	VARIANTARG* arguments = new VARIANTARG[2];
	
	VARIANTARG varg;
	VariantInit(&varg); 
	varg.vt = VT_R8; 
	varg.dblVal = 10.5; 
	arguments[0] = varg;
	
	VARIANTARG varg2;
	VariantInit(&varg2); 
	varg2.vt = VT_R8; 
	varg2.dblVal = 12.5; 
	arguments[1] = varg2;

	DISPPARAMS parameters;
	parameters.cArgs = 2; 
	parameters.rgvarg = arguments; 
	parameters.cNamedArgs = 0; 
	parameters.rgdispidNamedArgs = NULL;

	iDispatchInst->Invoke(dispid,
						IID_NULL,
						GetUserDefaultLCID(),
						DISPATCH_METHOD,
						&parameters, 
						&result, 
						NULL, 
						NULL);
	printf("%f + %f  = %f \n", varg.dblVal, varg2.dblVal, result.dblVal);

	//Calling the "getProgID" method
	methodName = L"getProgId";
	iDispatchInst->GetIDsOfNames(IID_NULL,&methodName,1,GetUserDefaultLCID(),&dispid);
	iDispatchInst->Invoke(dispid,
						IID_NULL,
						GetUserDefaultLCID(),
						DISPATCH_METHOD,
						&dispparamsNoArgs, 
						&result, 
						NULL, 
						NULL);
	wprintf(L"ProgID = %s%s", (wchar_t*)result.bstrVal, "\n");

	//Calling the "getVersionIndependentProgId" method
	methodName = L"getVersionIndependentProgId";
	iDispatchInst->GetIDsOfNames(IID_NULL,&methodName,1,GetUserDefaultLCID(),&dispid);
	iDispatchInst->Invoke(dispid,
						IID_NULL,
						GetUserDefaultLCID(),
						DISPATCH_METHOD,
						&dispparamsNoArgs, 
						&result, 
						NULL, 
						NULL);
	wprintf(L"VersionIndependentProgID = %s%s", (wchar_t*)result.bstrVal, "\n");

	//Calling the "getComServerDescription" method
	methodName = L"getComServerDescription";
	iDispatchInst->GetIDsOfNames(IID_NULL,&methodName,1,GetUserDefaultLCID(),&dispid);
	iDispatchInst->Invoke(dispid,
						IID_NULL,
						GetUserDefaultLCID(),
						DISPATCH_METHOD,
						&dispparamsNoArgs, 
						&result, 
						NULL, 
						NULL);
	wprintf(L"ComServerDescription = %s%s", (wchar_t*)result.bstrVal, "\n");

	//Calling the "getSafeArray" method
	arguments = new VARIANTARG[1];
	
	VARIANTARG vargNew;
	VariantInit(&vargNew); 
	vargNew.vt = VT_I8; 
	vargNew.intVal = 10; 
	arguments[0] = vargNew;

	parameters.cArgs = 1; 
	parameters.rgvarg = arguments; 
	parameters.cNamedArgs = 0; 
	parameters.rgdispidNamedArgs = NULL;


	methodName = L"getSafeArray";
	iDispatchInst->GetIDsOfNames(IID_NULL,&methodName,1,GetUserDefaultLCID(),&dispid);
	iDispatchInst->Invoke(dispid,
						IID_NULL,
						GetUserDefaultLCID(),
						DISPATCH_METHOD,
						&dispparamsNoArgs, 
						&result, 
						NULL, 
						NULL);	
	SAFEARRAY* safe = result.parray;

	int elementCount = safe->rgsabound->cElements;
	VARIANT* FAR rgvar = new VARIANT[elementCount];
	for(unsigned int k = 0; k < elementCount; ++k)
	    VariantInit(&rgvar[k]);

	for(long i=0; i < elementCount; i++)
	{
		SafeArrayGetElement(safe, &i, &rgvar[i]);
		wprintf(L"SafeArray [%i] = %s \n", i, rgvar[i], "\n");
	}

	for(i = 0; i < elementCount; ++i)
		VariantClear(&rgvar[i]);

	
	//Calling the "getEmptyVariant" method

	methodName = L"getEmptyVariant";
	iDispatchInst->GetIDsOfNames(IID_NULL,&methodName,1,GetUserDefaultLCID(),&dispid);
	iDispatchInst->Invoke(dispid,
						IID_NULL,
						GetUserDefaultLCID(),
						DISPATCH_METHOD,
						&dispparamsNoArgs, 
						&result, 
						NULL, 
						NULL);	
	VARIANT* variant = result.pvarVal;
	
	wprintf(L"getEmptyVariant = %s \n", variant, "\n");

	//Calling the "getIntegerVariant" method

	methodName = L"getIntegerVariant";
	iDispatchInst->GetIDsOfNames(IID_NULL,&methodName,1,GetUserDefaultLCID(),&dispid);
	iDispatchInst->Invoke(dispid,
						IID_NULL,
						GetUserDefaultLCID(),
						DISPATCH_METHOD,
						&dispparamsNoArgs, 
						&result, 
						NULL, 
						NULL);	
	int intVariantValue = result.intVal;
	
	wprintf(L"getIntegerVariant = %i \n", intVariantValue, "\n");

	// Free COM resources.
    CoUninitialize();

	std::cin.get();
	return 0;
}