Is it safe to use interfaces from dll

When I want to export a class to a DLL, is this the right approach to get it from an interface and return that interface using the exported function?

//exported dll function, which is used in the exe. function MyClass_Create: IMyClass; begin result := TMyClass.Create; end; 

What about memory management? Can I go through different interfaces and strings without worries and crashes?

 IMyClass = interface procedure SetString(aMsg: string); function GetString: string; procedure SetClass(aClass: ITestClass); function GetClass: ITestClass; end; 
+4
source share
2 answers

The use of such interfaces ensures that an object that implements the interface is created and freed in the same heap.

However, this will not solve the problem of distributing dynamic row types and releasing them on different heaps. There are many possible solutions for this, but, in my opinion, the best approach is to use WideString along the border of the module.

The WideString type is a wrapper around COM BSTR and is distributed on a common COM heap. You just need to use WideString for the interface. The interiors of implementing classes can use their own Delphi strings.

Just as strings represent problems, so are dynamic arrays. Attempting pas dynamic arrays across module boundaries is unsafe. There is no solution similar to WideString, which is convenient. You can use array options, but it's pretty awkward compared to WideString.

+3
source

Interface references are orthogonal to memory management. Usually you export a function that returns a link to the interface from the dll, and does not care about memory management. With reference to counting interfaces, you can be sure that an instance of an object that implements the interface will also be freed in the dll.

The lines are different. It doesn’t matter if you export an interface or export flat functions - the same restrictions apply.

By the way, your question title is incorrect; there are no "interface instances" in Delphi.

+5
source

Source: https://habr.com/ru/post/1390776/


All Articles