在 C 中创建一个有效的共享库

标签 c dll compilation shared-libraries loadlibrary

我正在做一些测试来学习如何创建共享库。 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位

你知道问题出在哪里吗,或者我做错了什么?

编辑1: 我在 windows 7 64bit 上,在编译器的 specs 文件中写道:“线程模型: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,但没有在我的系统上编译它们

编辑2: 阅读马克回答后。

主要.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__

主.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 描述如下:DLL Creation in MingW .

关于在 C 中创建一个有效的共享库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5233056/

相关文章:

C++ 从 DLL 实例化模板类

c++ - 如何创建可以独立于其依赖项使用的 C++ 库?

无法打印 C 中的用户定义函数

c++ - 将无符号整数舍入为 2 的幂序列

c - Valgrind 报告在函数中分配并在 main 中释放的结构泄漏

java - 编译程序后如何从源文件夹中获取 jar?

css - 编译时 Less 循环丢失 ")"

c - 冒泡排序C语言

C++ 通过引用 dll 中的函数传递 std::string

java - 如何在 ANTLR 的访问者模式下检查 token 的替代品?