Python Wrapper for C# Com Object

Thomas Heller theller at ctypes.org
Tue Jan 2 11:59:38 EST 2007


bg_ie at yahoo.com schrieb:
> bg_ie at yahoo.com skrev:
> 
>> Hi,
>>
>> I wish to write a Python wrapper for my C# COM object but am unsure
>> where to start. I have a dll and a tlb file, and I can use this object
>> in C via the following code -
>>
>> // ConsolApp.cpp : Defines the entry point for the console application.
>> //
>> #include "stdafx.h"
>> #include "windows.h"
>> #include "stdio.h"
>> #import "C:\Documents and Settings\X\Mina dokument\Visual Studio
>> 2005\Projects\X_COMObject\X_COMObject\bin\Debug\X_COMObject.tlb"
>> using namespace X_COMObject;
>>
>> int _tmain(int argc, _TCHAR* argv[])
>> {
>> 	CoInitialize(NULL);
>>
>> 	X_COMObject::XCOM_InterfacePtr p(__uuidof(X_COMObject::XCOM_Class));
>> 	XCOM_Interface *X_com_ptr ;
>> 	X_com_ptr = p ;
>> 	X_com_ptr->SetID(10);
>> 	int x = X_com_ptr->GetID();
>> 	printf("%d",x);
>> 	getchar();
>>
>> 	return 0;
>> }
>>
>> Can anyone offer me some tips as to how to do this in Python?
>>
>> Thanks very much for your help,
>>
>> Barry.
> 
> This is what I've done so far, but I know I'm not doing this correctly.
> Can anyone help me out?
> 
> #import pythoncom
> #pythoncom.CoInitialize()

The above is unneeded if you use comtypes as below (and is unneeded
when using pythoncom, as well).

> from comtypes.client import GetModule, CreateObject
> 
> module = GetModule("C:\\Documents and Settings\\X\\Mina
> dokument\\Visual Studio
> 2005\\Projects\\X_COMObject\\X_COMObject\\bin\\Debug\\X_COMObject.tlb")
> 
You don't intantiate the interface, you have to instantiate the COM object.
Something like

  CreateObject("XCOM_Class")

but of course you have to use the correct argument in the call - the progid
of the COM object.
Alternatively you can use the CoClass from the typelibrary, look into the
generated module in the comtypes\gen directory for a class derived from
comtypes.CoClass.

InternetExplorer, for example, can be started in these ways:

# using the progid:
ie = CreateObject("InternetExplorer.Application")

# using the clsid:
ie = CreateObject("{0002DF01-0000-0000-C000-000000000046}")


# using the coclass from the generated module:
mod = GetModule("shdocvw.dll")
ie = CreateObject(mod.InternetExplorer)

Thomas




More information about the Python-list mailing list