2

I have have a function in wrote in C++ that calls some functions in a old lib. This function creates some memory makes the calls and destroys the memory. To optimize this I would create an object that would keep the memory allocated until the object was destroyed. However I'm going to be calling this function from C# and don't believe I can export a Class, just functions or variables.

My idea is instead this; Think of the DLL as a class and the use local vars inside the scope of the dll to point to memory. Then have a function to create the memory, call the worker functions and another to destroy the memory when done with the DLL.

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

1
  • Are you creating & destroying the memory in the same place? Commented Apr 17, 2009 at 19:55

3 Answers 3

2

I prefer to write a managed wrapper in C++/CLI (formerly Managed C++), as it makes it much easier to explicitly do what you want with managed/unmanaged interoperability on the C++ side, and your C# doesn't get polluted with P/Invoke style code.

Edit Just noticed your comment "However I'm going to be calling this function from C# and don't believe I can export a Class, just functions or variables."

That's not entirely true - C# can import full classes from an assembly generated from C++/CLI code.

Sign up to request clarification or add additional context in comments.

1 Comment

@Smith325 - Yes. C++/CLI is a superset of C++ (in the same way C++ used to be a superset of C).
1

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

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

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

2 Comments

Could you provide links to some examles; e.g. Using pointers to C classes with IDisposable, using C++/CLI to make a wrapper.
I've got a sample on my blog (reedcopsey.com/?p=7) for the first. Any C++/CLI sample would work for the second - you'd just make it a managed class in C++/CLI instead of a native C++ class.
1

If you are willing to change the native C++ code, you could always export it as a COM interface which C# can consume.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.