在C中创建有效的共享库

时间:2011-03-08 13:23:11

标签: c dll compilation shared-libraries loadlibrary

我正在做一些测试来学习如何创建共享库。 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: 看完马克回答后。

main.h

#ifndef __MAIN_H__
#define __MAIN_H__

#include <windows.h>

#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 仍然得到同样的错误..

1 个答案:

答案 0 :(得分:1)

我相信您需要使用__declspec注释的Windows环境。如何创建共享库以及__declspec的使用在此处描述:DLL Creation in MingW