在C中创建有效的共享库

我正在做一些测试来学习如何创建共享库。 Code :: Blocks中共享库的模板就是这个

LIBRARY.C

// The functions contained in this file are pretty dummy // and are included only as a placeholder. Nevertheless, // they *will* get included in the shared library if you // don't remove them :) // // Obviously, you 'll have to write yourself the super-duper // functions to include in the resulting library... // Also, it's not necessary to write every function in this file. // Feel free to add more files in this project. They will be // included in the resulting library. // A function adding two integers and returning the result int SampleAddInt(int i1, int i2) { return i1 + i2; } // A function doing nothing ;) void SampleFunction1() { // insert code here } // A function always returning zero int SampleFunction2() { // insert code here return 0; } 

我试图编译它,并编译没有任何错误或警告。 但是当我尝试将它与python 3中的ctyped.cdll.LoadLibrary(“library path.dll”)一起使用时(实际上应该像C函数一样),它说它不是一个有效的win32应用程序。 python和code :: blocks都是32位(代码:用gcc编译块,我试图在我的系统上使用已安装的mingw版本,但是它给出了一个关于缺少库的错误),而我正在使用win 7 64位

你知道问题是什么,或者我做错了什么?

EDIT1:我在Windows 7 64bit上,在编译器的specs文件中写道:“线程模型:win32,gcc版本3.4.5(mingw-vista特殊r3)”和我用作命令

 gcc.exe -shared -o library.dll library.c 

在我使用的python中

 from ctypes import * lib = cdll.LoadLibrary("C:\\Users\\Francesco\\Desktop\\C programmi\\Python\\Ctypes DLL\\library.dll") 

而错误是

 WindowsError: [Error 193] %1 is not a valid Win32 application 

我从二进制包安装python3.1和mingw,而不是在我的系统上编译它们

EDIT2:看完Marc的回答。

main.h

 #ifndef __MAIN_H__ #define __MAIN_H__ #include  #ifdef BUILD_DLL #define DLL_EXPORT __declspec(dllexport) #else #define DLL_EXPORT __declspec(dllimport) #endif #ifdef __cplusplus extern "C" { #endif DLL_EXPORT int MySimpleSum(int A, int B); #ifdef __cplusplus } #endif #endif // __MAIN_H__ 

main.c中

 #include "main.h" // a sample exported function DLL_EXPORT int MySimpleSum(int A, int B) { return A+B; } 

编译选项

 gcc -c _DBUILD_DLL main.c gcc -shared -o library.dll main.o -Wl,--out-implib,liblibrary.a 

与gcc 4.5.2仍然得到相同的错误..

我相信在windows环境中你需要使用__declspec注释。 如何创建共享库并使用__declspec在此处描述: 在MingW中创建DLL 。