wrong answers only
wrong answers only

Reputation: 37

Using DLLs in C

This seems like a noob question, but all my searches return stuff about C++ or C# so I'm going to ask it here.

I have a DLL, SDL.dll, in the directory with my .c file. I want to import it to use. using is not supported, #import doesn't work.

Upvotes: 0

Views: 194

Answers (3)

user2088790
user2088790

Reputation:

Assuming you're using Visual Studio.

1.) Download  http://www.libsdl.org/release/SDL-1.2.15.zip
2.) unzip and install to for example C:\SDL-1.2.15
3.) In Visual Studio open the properties of the project goto C++ general and add C:\SDL-1.2.15\include to "Additional include directories".
4.) Goto the "Linker" tab and add C:\SDL-1.2.15\lib\x86 to "Additional library directories".
5.) Now go to "Input" under the Linker tab and add SDL.lib; SDLmain.lib to "Additional dependencies"
6.) Go to the "Build Events" tab and "Post build event" and add copy /y C:\SDL-1.2.15\lib\x86\SDL.dll "$(OutDir)

That should do get your SDL working for Visual Studio in 32bit

On Linux if SDL is already installed just type "g++ -02 -o foo foo.cpp -lSDL"

Upvotes: 0

jdehaan
jdehaan

Reputation: 19938

No directive in the source will help you, you can either

  • link to the DLL, use a so-called lib file for this. (This is a statically dynamic linking)
  • use LoadLibrary/FreeLibrary and GetProcAddress to map the addresses of functions to function pointers (true dynamic linking)

In the first case you also need an appropriate header file which matches the platform and version of the DLL used.

The second solution will work if you drop-in a newer version of the DLL as long as the prototypes of the functions used match.

This assumes you are under Windows, which is probably the case if you have a *.dll and not an *.so (shared object) file. (For Linux systems, you can include dlfcn.h and use dlopen/dlclose/dlsym instead of LoadLibrary/FreeLibrary/GetProcAddress with a slightly different syntax, check the doc)

Upvotes: 1

Grantly
Grantly

Reputation: 2556

this is quite possible assuming your DLL is in the correct form (the same standards as Windows API DLLs for example)

you need to declare you functions - perhaps in a header file, like this:

typedef void (CALLBACK *functionnameptr)(char *, int),

Then you use LoadLibrary to load the DLL, and provide a Handle to it:

handle = LoadLibrary("SDL.DLL");

Then you use GetProcAddress(handle,"real function name in DLL") like this:

functionnameptr lptrfunction;

lptrfunction = GetProcAddress(handle,"real function name in DLL");

Now you can use the lptrfunction as you would normally use a function in C

Upvotes: 0

Related Questions