cpp中的__stdcall、__declspec(dllexport)、__declspec(dllimport)

⌚Time: 2023-08-11 15:32:35

👨‍💻Author: Jack Ge

__stdcall

函数调用约定

被这个关键字修饰的函数,其参数都是从右向左通过堆栈传递的(__fastcall 的前面部分由ecx,edx传), 函数调用在返回前要由被调用者清理堆栈。

__stdcall是函数调用约定的一种,函数调用约定主要约束了两件事:

1.参数传递顺序

2.调用堆栈由谁(调用函数或被调用函数)清理

常见的函数调用约定:stdcall cdecl fastcall thiscall naked call

__stdcall表示

1.参数从右向左压入堆栈

2.函数被调用者修改堆栈

3.函数名(在编译器这个层次)自动加前导的下划线,后面紧跟一个@符号,其后紧跟着参数的尺寸

在win32应用程序里,宏APIENTRY,WINAPI,都表示_stdcall,非常常见。

__declspec(dllexport)、__declspec(dllimport)

Microsoft 专用

dllexport 和 dllimport 存储类特性是 C 和 C++ 语言的 Microsoft 专用扩展


// MathLibrary.h - Contains declarations of math functions

#pragma once



#ifdef MATHLIBRARY_EXPORTS

#define MATHLIBRARY_API __declspec(dllexport)

#else

#define MATHLIBRARY_API __declspec(dllimport)

#endif



// The Fibonacci recurrence relation describes a sequence F

// where F(n) is { n = 0, a

//               { n = 1, b

//               { n > 1, F(n-2) + F(n-1)

// for some initial integral values a and b.

// If the sequence is initialized F(0) = 1, F(1) = 1,

// then this relation produces the well-known Fibonacci

// sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, ...



// Initialize a Fibonacci relation sequence

// such that F(0) = a, F(1) = b.

// This function must be called before any other function.

extern "C" MATHLIBRARY_API void fibonacci_init(

    const unsigned long long a, const unsigned long long b);



// Produce the next value in the sequence.

// Returns true on success and updates current value and index;

// false on overflow, leaves current value and index unchanged.

extern "C" MATHLIBRARY_API bool fibonacci_next();



// Get the current value in the sequence.

extern "C" MATHLIBRARY_API unsigned long long fibonacci_current();



// Get the position of the current value in the sequence.

extern "C" MATHLIBRARY_API unsigned fibonacci_index();

此头文件声明一些函数以生成通用 Fibonacci 序列,给定了两个初始值。 调用 fibonacci_init(1, 1) 会生成熟悉的 Fibonacci 数字序列。

请注意文件顶部的预处理器语句。 DLL 项目的新项目模板会将 _EXPORTS 添加到定义预处理器宏。 在此示例中,Visual Studio 在生成 MathLibrary DLL 项目时定义 MATHLIBRARY_EXPORTS。

定义 MATHLIBRARY_EXPORTS 宏时,MATHLIBRARY_API 宏会对函数声明设置 __declspec(dllexport) 修饰符。 此修饰符指示编译器和链接器从 DLL 导出函数或变量,以便其他应用程序可以使用它。 如果未定义 MATHLIBRARY_EXPORTS(例如,当客户端应用程序包含头文件时),MATHLIBRARY_API 会将 __declspec(dllimport) 修饰符应用于声明。 此修饰符可优化应用程序中函数或变量的导入。 有关详细信息,请参阅 dllexport、dllimport。

我使用


extern "C" MATHLIBRARY_API unsigned _stdcall fibonacci_index();

将函数进行导出,得到的函数修饰名_fibonacci_index@0

使用


MATHLIBRARY_API  unsigned long long fibonacci_current();

?fibonacci_current@@YA_KXZ

使用


extern "C" MATHLIBRARY_API bool fibonacci_next();

fibonacci_next

使用__declspec(dllimport) 导入函数,函数会添加前缀__imp,提示


错误  1   error LNK2019: 无法解析的外部符号 "__declspec(dllimport) void __cdecl function(void)" (__imp_?function@@YAXXZ),该符号在函数 _wmain 中被引用