I need to keep references in unmanaged code to objects on managed side, like handles. There are going to be approx. 10,000,000 objects.
I'm not familiar with interop, initially I thought it was as simple as declaring
ref SomeClass
on C# side and
void*
in C++.
Then I realized
SomeClass
would maybe need to have a representation in C++, that it wouldn't work with
void*
.
Am I forced to find a "common denominator" between the type representations in C# and C++? The common denominator would be the type
System.Object
or the specific specific, per object type, or hopefully with
void*
no type relationship would matter.
Another issue: after some research I found out that I should probably pin the object in memory on managed side. Maybe something akin to
pin_ptr<T>
would exist for C#? Or no pinning is necessary?
Or maybe using
IntPtr
would save the day? And I'd convert back and forth between
IntPtr
and
void*
.
I haven't tried anything as I don't know how to approach this. Especially as I've read that it could all seem to work out well until GC relocates variables and it messes all up.
And at the same time I'd like to take the path of the most performant solution, like avoiding ops any time the object is referenced, like unforseen checkings.
What I have tried:
The answer at
https://stackoverflow.com/questions/19696459/pass-by-reference-from-c-through-c-l-i-to-unmanaged-c is inconclusive as it doesn't say anything about pinning.
If pinning is necessary, I could use the answer at
https://stackoverflow.com/questions/35603788/is-it-possible-to-create-pinned-pointer-in-c
Ultimately, hopefully pinning is not necessary and neither any type conversion. I would get away with using
IntPtr
and
void*
converting as specified at
https://docs.microsoft.com/en-us/dotnet/api/system.intptr.op_explicit?redirectedfrom=MSDN&view=net-5.0#System_IntPtr_op_Explicit_System_IntPtr__System_Void_
Looking at
https://docs.microsoft.com/en-us/dotnet/api/system.intptr?view=net-5.0 IntPtr
is a struct that potentially adds complexity as compared to a simple
ref
-
void*
option. But it probably there's no way around what
IntPtr
accomplishes