简体   繁体   中英

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?

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.

My solution to a similar problem, I had some old code in Fortan. I convert this code to c, then created a managed c++ project. In c#, I called this manged c++ project.

the c# code looks like this:

unsafe
{
double* input = (double*)utils.Memory.Alloc(sizeof(double) * n);
double* output = (double*)utils.Memory.Alloc(sizeof(double) * n);
//calling the c++ code
c_plus_plus.code(input,output); //now output contains the output
// (you can use the same array as input and output
}

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM