Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何在运行时将dll链接到exe文件?_C_Dll_Runtime.exec - Fatal编程技术网

C 如何在运行时将dll链接到exe文件?

C 如何在运行时将dll链接到exe文件?,c,dll,runtime.exec,C,Dll,Runtime.exec,我是编程新手,我创建了一个dll项目,在其中,我将只打印一行。在应用程序项目中,我调用了dll项目中定义的函数 我的问题是,在构建dll项目后不久,我将获得dll文件。但是,当我构建主应用程序(即应用程序项目)时,我得到了以下错误 --------------------Configuration: test_bench - Win32 Debug-------------------- Compiling... main.c Linking... main.obj : error LNK20

我是编程新手,我创建了一个dll项目,在其中,我将只打印一行。在应用程序项目中,我调用了dll项目中定义的函数

我的问题是,在构建dll项目后不久,我将获得dll文件。但是,当我构建主应用程序(即应用程序项目)时,我得到了以下错误

--------------------Configuration: test_bench - Win32 Debug-------------------- 
Compiling...
main.c
Linking...
main.obj : error LNK2001: unresolved external symbol _print_dll
../../exec/test_bench.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.

test_bench.exe - 2 error(s), 0 warning(s)
如果我在构建之前链接obj,它就会被构建。但是,如果我更改了dll项目的代码,我必须再次重新构建主项目,这在运行dll时应该是不必要的


请帮助我实现此功能

此错误表示您没有在可执行文件中链接库DLL,这就是它找不到函数print\u DLL的原因

您可以通过在Windows中动态加载库

下面是一个如何执行的示例:

要在运行时链接dll项目,需要在主文件中实现运行时链接。如果实现了运行时链接方式,则无需每次都重新构建项目。 对于运行时链接,您需要以下函数

#include <dlfcn.h>

   void *dlopen(const char *filename, int flag);

   char *dlerror(void);

   void *dlsym(void *handle, const char *symbol); //symbol is your function name

   int dlclose(void *handle);

   Link with -ldl.
有关更多详细信息,请参阅手册页。 但是,在更改代码时,如果更改函数名,则应使用相同的名称来代替符号。

我编写了一个小的二进制模板,以帮助处理与dlopen相关的调用。您需要根据您的特定用例调整它,因为它只处理字符串,但我发现它在很多情况下都很方便

用法:dlopener/path/to/library.extension函数_name[args…]

注意:对于某些WIN32函数cdecl调用约定IIRC,需要使用与push不同的asm机制来获取寄存器中的值,而不是堆栈中的值

//gcc -rdynamic -o dlopener dlopener.c -ldl
#include <dlfcn.h> /*for dlopen,dlsym,dlclose*/

int main(int argc, char **argv){

   /* get a "handle" for a shared library*/
   void *handle = dlopen(argv[1], RTLD_LAZY);

   /* make sure we got a handle before continuing*/
   if (! handle) return 1;

   /*undefined, but workable solution : POSIX.1-2003 (Technical Corrigendum 1) */
   void* (*f)()=dlsym(handle, argv[2]);

   /*now call the function f(argv[3],argv[4],...argv[argc]); */
   //TODO convert args to unsigned char representations for other types 
   while (argc > 2)  /*ugh, have to use asm to preserve stack*/
      asm("push %0"::"r"(argv[argc--])); /*from right to left*/

   asm("call *%0"::"r"(f)); //TODO  "=a"(ret) where is uchar[XXX]

   /*remember that shared library we opened?*/
   dlclose(handle);

   return 0;
}