可以在DLL中使用,主应用程序提供的外部函数而不是将DLL函数导出到应用程序吗?

例如,在我的静态库中

void function (void); function(); 

并且function()存在于主应用程序中。

但是,如果我将其构建为DLL,则链接器会抱怨DLL上的函数未定义。

是的,但这是hackish。

在DLL中:

 typedef void(*funcPtr)(void); // Declare a variable named "ptrFunction" which is a pointer to a function which takes void as parameter and returns void funcPtr ptrFunction; // setter for ptrFunction; will be called from the .exe void DLL_EXPORT setFunction(funcPtr f){ptrFunction f;} // You can now use function() through ptrFunction foo(){ ptrFunction(); } 

然后从.exe调用setFunction。

 void function(){ // implementation here } int main(){ setFunction(&function); // now the dll knows the adress of function() foo(); // calls foo() in dll, which calls function() in the .exe .... } 

太好了,对吧? :/你应该重构你的代码,以便function()在另一个DLL中,但它取决于。

是的你可以,但如果你不需要,我强烈建议不要这样做。 它很繁琐,感觉你需要更好地理清你的依赖关系。

要做到这一点,你必须使用LIB.EXE从一个二进制文件的目标文件创建一个导入库,然后再实际链接它; 使用此导入库链接其他二进制文件并为其他二进制文件创建导入库; 最后使用其他库的导入库链接原始二进制文件。

例如

exe.c:

 #include  void __declspec(dllimport) dllfn(void); void __declspec(dllexport) exefn(void) { puts("Hello, world!"); } int main(void) { dllfn(); return 0; } 

cl /c exe.c编译。 exe.obj已创建。

exe.def:

 LIBRARY exe.exe 

使用lib /def:exe.def exe.obj创建导入库。 exe.libexe.exp已创建。

dll.c:

 void __declspec(dllimport) exefn(void); void __declspec(dllexport) dllfn(void) { exefn(); } 

cl /c dll.c编译。 dll.obj已创建。

使用link /dll dll.obj exe.lib链接DLL。 创建了dll.dlldll.libdll.exp

链接EXE与link exe.obj dll.libexe.exe已创建。 ( exe.libexe.exp也被重新创建。)

运行exe,注意Hello, world! 输出。