tranmq
tranmq

Reputation: 15658

Marshalling a class intance's pointer between C++ and C#

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.

Upvotes: 3

Views: 3404

Answers (2)

JaredPar
JaredPar

Reputation: 754575

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);

Upvotes: 1

Mark P Neyer
Mark P Neyer

Reputation: 1009

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

Upvotes: 1

Related Questions