Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 723
tranmq Avatar asked May 27 '26 12:05

tranmq


2 Answers

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

like image 98
Mark P Neyer Avatar answered May 31 '26 13:05

Mark P Neyer


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);
like image 31
JaredPar Avatar answered May 31 '26 11:05

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!