Getting object functionality from C ++ code in C #

I have a function in C ++ writing that calls some functions in the old lib. This function creates some memory that calls and destroys memory. To optimize this, I would create an object that would retain memory until the object was destroyed. However, I will call this function with C # and I do not believe that I can export a class, just functions or variables.

My idea is as follows; Think of a DLL as a class and how to use local classes inside the dll to point to memory. Then create a function to create memory, call working functions and another to destroy memory when done with the DLL.

Is this a good approach? Is there a better way?

+2
source share
4 answers

I prefer to write a managed shell in C ++ / CLI (formerly Managed C ++), since it makes it much easier to explicitly do what you want with managed / unmanaged compatibility on the C ++ side, and your C # is not polluted with P / Invoke style code.

Edit I just noticed your comment "However, I will call this function with C # and I do not believe that I can export a class, just functions or variables."

This is not entirely true - C # can import complete classes from an assembly generated from C ++ / CLI code.

+2
source

Create a C # class that implements IDisposable. You can wrap a simple C API around your C ++ object, so when you create an instance, it returns a pointer to a C ++ class, and when you Dispose () your C # class, it removes the pointer.

You can always dereference this pointer to call methods in your C ++ class.

Another good alternative is to simply use C ++ / CLI to make a wrapper for your C ++ class. Handling this type of situation is much simpler.

+1
source

If you want to change your own C ++ code, you can always export it as a COM interface that C # can use.

+1
source

All Articles