Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Using TlbImp.exe-Generated Interop Assemblies

Using TlbImp.exe-Generated Interop Assemblies

Visual Studio .NET 2003
Note   Because of limitations with TlbImp.exe, the best way to generate an interop assembly with Managed Extensions is by using custom runtime callable wrappers. For details, see Implementing a Custom Runtime Callable Wrapper

TlbImp.exe can generate an interop assembly for the CustomDate component server. The runtime marshaler cannot marshal some data types, so TlbImp.exe replaces the data type with System::IntPtr.

For the ICustomDate interface, consider the following IDL:

HRESULT GetDate([out,ref] CUSTOM_DATE ** pDate);
HRESULT PutDate([in,ref] CUSTOM_DATE * pDate);
HRESULT GetDates([out]short *n,[out,size_is(,*n)]CUSTOM_DATE **dates);

TlbImp.exe translates it as:

void GetDate(IntPtr pDate);
void PutDate(int __gc * pDate);
void GetDates(short __gc * n, IntPtr dates);

The following example code will be translated by TlbImp.exe:

CUSTOM_DATE __nogc *pDate = NULL;

// Stores a pointer to the pDate pointer in an IntPtr
IntPtr p = __nogc new IntPtr(&pDate);

c->GetDate(p);
Console::WriteLine("Date retrieved: {0}/{1}/{2}",
      __box(pDate->day),
      __box(pDate->month),
      __box(pDate->year));
pDate->day++;
Console::WriteLine("Modified date: {0}/{1}/{2}",
      __box(pDate->day),
      __box(pDate->month),
      __box(pDate->year));
c->PutDate((int *)p.ToInt32());
CoTaskMemFree(pDate);

short n;
c->GetDates(&n,p);
for(int i=0;i<n;i++)
{
   Console::WriteLine("{0}-{1}-{2}",
      __box(pDate[i].day),
      __box(pDate[i].month),
      __box(pDate[i].year));
}
CoTaskMemFree(pDate);

TlbImp.exe passes the IntPtr field that stores the pointer value by value to the COM component. When the call returns, the value of the pointer is lost, and the pointer remains NULL. If the COM component actually allocates memory, it will be leaked. To avoid this when using TlbImp.exe, you would need to manually edit the generated interop assembly to change the method definitions.

Also, the data type is the unmanaged structure CUSTOM_DATE. In this example, it would be preferable to use System::DateTime instead of CUSTOM_DATE.

Go to the next step | Go to the previous step

See Also

Managed Extensions for C++ and COM Interoperability Tutorial

Show:
© 2015 Microsoft