views:

647

answers:

2

I have an ActiveX control (written in C++) and reference it's RCW assemblies (created by aximp.exe) from a C# project.

In the C++ code implementing the Ax control, I have a class implementing an interface which is exposed as a property of the Ax control.

Looking at the generated RCW assemblies, I see the interface. And I can attempt to declare a variable of its type.

Now, if I only have a pointer to the instance of the C++ class implementing the interface in memory, is it possible to marshal its data into the managed C# object representing the interface using that pointer?

Please note that it's not the interface pointer. It's the pointer to the instance of the class that I have.

+1  A: 

You might want to give C++ / CLI a try. Writing code that interoperates between C++ and C# is a snap.

Mark P Neyer
I'm currently doing that. I have an intermediate managed C++ project to bridge the two. But I'm hoping that there's a better, cleaner way to achieve it.
mqbt
The best, cleanest way to achieve interop between managed and unmanaged types is a C++/CLI wrapper.
Randolpho
A: 

I think there are 2 questions here.

Can you marshal a "this" pointer to managed code but not as a specific interface

Yes. This is possible by implementing a COM interface in the C# application and then passing "this" as one of the parameters. The managed type accepting the "this" pointer should be Int32 or Int64 (unsigned OK) depending on your platform

Can I do anything useful with this pointer

Yes and No.

You can't directly call any instance methods on this pointer because there is no type to which you can cast the value. So it cannot be used like a COM interface would be used.

What you can do is define a set of extern "C" methods in your native application which take the a pointer of that type as the first parameter and then call a particular method on that object. You can then use C# to PInvoke into that method

C++

void SomeType_SomeMethod(SomeType* pSomeType) {
  pSomeType->SomeMethod();
}

C#

[DllImport("YourDll.dll")]
public static extern void SomeType_SomeMethod(IntPtr pSomeType);
JaredPar
Passing the pointer to the C# implementer of the COM interface? Then how is the pointer used in the class?
mqbt
For the 2nd option, I achieved the same affect by mapping delegates in the managed C# class to function pointers in the unmanaged C++ class.Thanks for the suggestions.
mqbt