Getting Object Functionality out of C++ code in C#

☆樱花仙子☆ 提交于 2019-12-01 08:16:10

问题


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:


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.




回答2:


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.




回答3:


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




回答4:


See answers at Using C++ Class DLL in C# Application



来源:https://stackoverflow.com/questions/761930/getting-object-functionality-out-of-c-code-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!