1

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

图书馆.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 位的(code:blocks 使用 gcc 编译,我尝试在我的系统上使用已安装的 mingw 版本,但它给出了一些关于缺少库的错误),而我正在使用 win 7 64位

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

EDIT1:我在 Windows 7 64bit 上,在编译器的规范文件中写道:“线程模型:win32,gcc 版本 3.4.5(mingw-vista special 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:阅读马克回答后。

主文件

#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__

主程序

#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 仍然会出现相同的错误..

4

1 回答 1

1

我相信在windows环境下你需要使用__declspec注解。__declspec此处描述了如何创建共享库及其使用: MingW 中的 DLL Creation

于 2011-03-08T20:39:51.203 回答