问题描述
设计一个用于dll的C API的最好方法是处理传递运行时依赖(FILE *,由malloc返回的指针等)的问题。例如,如果两个DLL与不同版本的运行时链接,我的理解是您不能将FILE *从一个DLL传递到另一个dll。是唯一的解决方案是使用依赖于Windows的API(可以保证在dll中工作)? C API已经存在并且已经成熟,但是主要是由unix POV设计的(当然还需要在unix上工作)。
您要求C,而不是C ++解决方案。
在C中执行此类事情的常用方法是: p>
-
设计模块API,简单地不需要CRT对象。获取在原始C类型中传递的东西 - 即让消费者加载文件,并简单地传递你的指针。或者,让消费者在内部传递一个完全限定的文件名,即打开,读取和关闭。
-
其他c模块使用的方法, MS机柜SD和OpenSSL库iirc的一部分,让消费应用程序传递给初始化函数的函数指针。所以,任何传递FILE *的API在初始化过程中的某个时候都会使用一个指向结构体的指针,该函数指针与fread,fopen等的签名相匹配。当处理外部文件*时,dll始终使用传入的功能而不是CRT功能。
使用这样一些简单的技巧,您可以使您的C DLLs界面完全独立于主机CRT - 或者实际上要求主机用C或C ++编写。
What is the best way to design a C API for dlls which deals with the problem of passing "objects" which are C runtime dependent (FILE*, pointer returned by malloc, etc...). For example, if two dlls are linked with a different version of the runtime, my understanding is that you cannot pass a FILE* from one dll to the other safely.
Is the only solution to use windows-dependent API (which are guaranteed to work across dlls) ? The C API already exists and is mature, but was designed from a unix POV, mostly (and still has to work on unix, of course).
You asked for a C, not a C++ solution.
The usual method(s) for doing this kind of thing in C are:
Design the modules API to simply not require CRT objects. Get stuff passed accross in raw C types - i.e. get the consumer to load the file and simply pass you the pointer. Or, get the consumer to pass a fully qualified file name, that is opened , read, and closed, internally.
An approach used by other c modules, the MS cabinet SD and parts of the OpenSSL library iirc come to mind, get the consuming application to pass in pointers to functions to the initialization function. So, any API you pass a FILE* to would at some point during initialization have taken a pointer to a struct with function pointers matching the signatures of fread, fopen etc. When dealing with the external FILE*s the dll always uses the passed in functions rather than the CRT functions.
With some simple tricks like this you can make your C DLLs interface entirely independent of the hosts CRT - or in fact require the host to be written in C or C++ at all.
这篇关于C运行时对象,dll边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!