COM interop: Returning an object of a user-defined class allowed?

B

Boris

The .NET documentation talks about blittable and non-blittable types. While
objects of type System::Object* are non-blittable it doesn't say anything
about objects of user-defined classes. All the COM interop examples I've
seen always return objects of types of the System namespace. But what if you
want to return an object of a user-defined managed class?

public __gc class A {
public:
int i;
A(int value) : i(value) { }
};

public __gc class B {
A *a;
public:
B() { a = new A(0); }
__property A *get_a() { return a; }
};

Now let's say you have a COM client (eg. in Visual Basic 6) and you do this:

Dim objB as Object
Set objB = CreateObject("B")
B.a.i = 1

Is this safe? After all the property a returns a pointer to a managed
object. And while you work with this pointer in the COM client you don't
know what the garbage collector does?

After reading all day in the .NET documentation I think the COM client gets
a pointer to a COM wrapper class which has again a pointer to the managed
object of type A. So if the garbage collector moves the object around the
pointer in the wrapper class is updated. The wrapper class however is never
moved around so the COM client can safely use the property a. However I also
read about GCHandle and gcroot<> which seem to say that you have to fix
objects of managed types if you want to pass them to unmanaged code. Anyone
knows what is right?

Thanks in advance,
Boris
 
B

Boris

Boris said:
The .NET documentation talks about blittable and non-blittable types.
While objects of type System::Object* are non-blittable it doesn't
say anything about objects of user-defined classes. All the COM
interop examples I've seen always return objects of types of the
System namespace. But what if you want to return an object of a
user-defined managed class?

Just to answer my own question: It's no problem to return an object of a
user-defined type to COM. The object is marshalled automatically and can be
used in COM. GCHandle and gcroot<> seem only to be necessary when you don't
work with COM but eg. call DLL functions directly.

Boris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top