Search code examples
c#interoppinvokemarshallingdllimport

Pass C# reference to C++ pointer and back


I would like to pass C# reference to C/C++ code(pointer), and than get it back from pointer to C#reference. I have many pairs (uint,Object). I created sorting mechanism in C code, because its much faster than C#. There is only key(uint) and value(object reference) needed. C code is using key for sorting, and is not changing the value(pointer). Is there any simple way to do it? Do i need to use marshalling? C function will be called many times(maybe even a million times), so i am affraid it will be with marshalling too slow, and i don´t even know how to do it with marshalling. I believe when objects address is changed by GC, address of C# reference is not changed. So there will not be needed to place object in pined memory. Am i right about this? Now i am able to call C function using DllImport, i am able to store C# reference to C pointer, but i am not able to get address stored in C pointer to C# reference.

Any ideas on how to do this?


Solution

  • It is not possible to pass any variables directly from manged c# code to native c++ code. The solution is pinvoke where you can marshal the data.

    This works fine but you should know that this is not everytime the fastes solution. On every call the memory must be copied and maybe converted depending on the data types.