tags:

views:

69

answers:

1
+2  A: 

You will find the command line options of Microsoft's C++ compiler here.

Consider the following switches for cl:

/nologo /GS /fp:precise /Zc:forScope /Gd

...and link your file using

/NOLOGO /OUT:"your.dll" /DLL <your lib files> /SUBSYSTEM:WINDOWS /MACHINE:X86 /DYNAMICBASE

Please have a look at what those options mean in detail, I just listed common ones. You should be aware of their effect nonetheless, so try to avoid copy&paste and make sure it's really what you need - the documentation linked above will help you. This is just a setup I use more or less often.

Be advised that you can always open Visual Studio, configure build options, and copy the command line invokations from the project configuration dialog.

Edit: Ok, here is some more advice, given the new information you've edited into your original question. I took the example code of your simple DLL and pasted it into a source file, and made two changes:

#include <windows.h>
BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
    return TRUE;  
} 

extern "C" __declspec(dllexport) int __stdcall multiply(int num1, int num2)
{
    return num1 * num2;  
} 

First of all, I usually expect functions exported from a DLL to use stdcall calling convention, just because it's a common thing in Windows and there are languages who inherently cannot cope with cdecl, seeing as they only know stdcall. So that's one change I made.

Second, to make exports more friendly, I specified extern "C" to get rid of name mangling. I then proceeded to compile the code from the command line like this:

cl /nologo /GS /Zc:forScope /Gd c.cpp /link /OUT:"foobar.dll" /DL kernel32.lib /SUBSYSTEM:WINDOWS /MACHINE:X86

If you use the DUMPBIN tool from the Visual Studio toolset, you can check your DLL for exports:

dumpbin /EXPORTS foobar.dll

Seeing something like this...

ordinal hint RVA      name
    1    0 00001010 ?multiply@@YGHHH@Z

...you can notice the exported name got mangled. You'll usually want clear names for exports, so either use a DEF file to specify exports in more details, or the shortcut from above.

Afterwards, I end up with a DLL that I can load into Python like this:

In [1]: import ctypes

In [2]: dll = ctypes.windll.LoadLibrary("foobar.dll")

In [3]: dll.multiply
Out[3]: <_FuncPtr object at 0x0928BEF3>

In [4]: dll.multiply(5, 5)
Out[4]: 25

Note that I'm using ctypes.windll here, which implies stdcall.

Jim Brissom
@Jim: thank you so very much!
serina
If you find my answer helpful, you are free to click to accept it ;)
Jim Brissom
@Jim: I can use the cl now, but it won't work, gcc works fine...
serina
Can you edit your question to hint at the current state or your problem, i.e. including what you have tried so far, what error messages you get, and what/why you think it is not working.
Jim Brissom
@Jim Brissom: Sure, sorry, I went out for something, so I didn't not see your post, I will post them now, many thanks to you
serina