使用dll的接口是安全的 [英] Is it safe to use interfaces from dll

查看:106
本文介绍了使用dll的接口是安全的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想在DLL中导出一个类时,它是从一个接口派生出来并通过导出的函数返回该接口的正确方法吗?

When I want to export a class within a DLL, is it the right approach to derive it from an interface and return that interface by an exported function?

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

内存管理如何?我可以不传入不同的接口和字符串,而不用担心和崩溃?

What about the memory management? Can I than pass in/out 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;


推荐答案

使用这样的接口将确保实现界面将在同一个堆上创建并释放。

Using interfaces like this will ensure that the object implementing the interface will be created and freed on the same heap.

但是,这不会解决在不同堆上分配和释放的动态字符串类型的问题。有许多可能的解决方案,但在我看来,最好的方法是在模块边界中使用WideString。

However, this will not solve the problem of dynamic string types being allocated and deallocated on different heaps. There are many possible solutions to this, but in my view the best approach is to use WideString across the module boundary.

WideString类型是COM BSTR周围的包装器分配在共享COM堆上。您只需要使用WideString作为接口。实现类的内部可以使用本机Delphi字符串。

The WideString type is a wrapper around the COM BSTR and is allocated on the shared COM heap. You only need to use WideString for the interface. The internals of the implementing classes can use native Delphi strings.

正如字符串存在问题一样,动态数组。尝试在模块边界上放置动态数组是不安全的。没有解决方案对WideString的方便。您可以使用变体数组,但与WideString相比,它们相当笨重。

Just as strings present problems so do dynamic arrays. Attempting to pas dynamic arrays across module boundaries is not safe. There is no solution analagous to WideString that is as convenient. You can use variant arrays but that's pretty clunky in comparison to WideString.

这篇关于使用dll的接口是安全的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆