This is the mail archive of the
mailing list for the Cygwin project.
Re: How to create a .dll which contains a function defined in another program?
- From: Brian Dessent <brian at dessent dot net>
- To: cygwin at cygwin dot com
- Date: Wed, 13 Jul 2005 17:08:14 -0700
- Subject: Re: How to create a .dll which contains a function defined in another program?
- References: <200507131535.j6DFZqwi005679@diometes.ucdavis.edu>
- Reply-to: cygwin at cygwin dot com
Yu-Cheng Chou wrote:
> bar() is in the main.c which is compiled using VC++.
> bar() is called inside module.c which is compiled as module.dll using
> cygwin's gcc.
> module.dll is loaded by LoadLibrary() in main.exe.
There are two ways to do this:
1. Create an import library for the .exe file, and link against that
during the link of module.dll. With gcc, you just add
"-Wl,--output-implib,main.a" to the link command of main.exe. I have no
idea how you do this with VC++, so you're on your own there. Note that
this is rather brittle, because it hard codes the name of the .exe into
the DLL, so that if the .exe is renamed the DLL will no longer work.
2. Use GetProcAddress() in module.c to get the address of bar() and then
call it. Note that the HMODULE here is the handle of the .exe, not the
dll. You should be able to get this with GetModuleHandle(NULL) I
think. The downside here is that if you have more than a couple of
imports from the .exe that you want to use, it will be a pain setting up
function pointers and calling GetProcAddress for each one.
Both of these solutions are not that great. For this reason it's
usually considered bad design under windows to have DLLs that import
from their parent .exe files. To get around this, the normal method is
to isolate the desired functionality (in this case bar()) and put it in
its own bar.dll, then main.exe and module.dll both import bar() from
bar.dll. Another alternative is by using callbacks. For example, when
you call a function in module.dll from main.exe, you pass as a parameter
the address of bar() in main.exe.
Unsubscribe info: http://cygwin.com/ml/#unsubscribe-simple
Problem reports: http://cygwin.com/problems.html