Keep the class state in C++ after Returning to C#
I have a C++ as the backend and C# as the front end, I use pinvoke interop mechanism to communicate between the native and managed code.
The issue now is tha开发者_Go百科t there are really two parts of computation done by the C++ backend, the initialization part and the compute-on-the-fly part. The initialization needs to be done only once, but it takes a long time to do, whereas the compute-on-the-fly part takes a very short time to do, but it needs to be done over and over again.
And the C++ code as to be kept as it is and can't be rewritten into C# code.
I can modify both the C++ and C# code as I have them at my disposal.
I know how to do static interop, but I don't know how to do this kind of state-full interop. Any idea?
You could write a wrapper around your C++ class(es) in C++/CLI thus providing true CLR types. You can than manage their lifecycle in C# seamlessly.
- There is quite some information on the web for it: here or here (just google "C++/CLI wrapper").
- And, naturally, on stackoverflow: here.
Unless there is some nifty tool, you would have to write this wrapper yourself.
Alternatively, you could write a wrapper function (or a set thereof) around your C++ classes, possibly only exposing the minimum required functionality as "C" functions. You would then passe out a "HANDLE" (Int32, IntPtr, whatever) out of the init-function and requiring it as input for the compute-function. You would have to manage those internally in the wrapper functions (you might also want to provide a cleanup-function).
精彩评论