c++ - 能否从 DLL 中动态调用对象?

标签 c++ winapi dll

假设我有一个包含这个的 DLL 权限:

//DLL 
 class foo { 
  static __declspec int Add(int a, int b)
  { 
  return a+b
  }
 }

如何调用它调用 GetProc 地址?即:

HINSTANCE hFoo = LoadLibrary("Foo.dll");
int* proc = NULL;
proc = (int*) GetProcAddress(hFoo, ??????);
 //Main Exec linked to dll

您究竟如何使用 GetProcAddress 获取在 dll 中创建的类的地址?

最佳答案

edtheprogrammerguy 是对的。

以下是有关如何正确公开类的更多信息:

您需要在属性前加上前缀:

__declspec(dllexport)...

您要公开的所有功能。

参见 this .

C 函数示例:

__declspec(dllexport) int __cdecl Add(int a, int b)
{
  return (a + b);
}  

这可以使用 MACROS 进行简化:一切都在这个 helpful page 上进行了解释.


对于 C++ 类,您只需为每个类(而不是每个方法)添加前缀

我通常这样做:

Note : The following also ensures portability...

包含文件:

// my_macros.h
//
// Stuffs required under Windoz to export classes properly
// from the shared library...
// USAGE :
//      - Add "-DBUILD_LIB" to the compiler options
//
#ifdef __WIN32__
#ifdef BUILD_LIB
#define LIB_CLASS __declspec(dllexport)
#else
#define LIB_CLASS __declspec(dllimport)
#endif
#else
#define LIB_CLASS       // Linux & other Unices : leave it blank !
#endif

用法:

#include "my_macros.h"

class LIB_CLASS MyClass {
}

然后,要构建,只需:

  • 将选项 -DBUILD_LIB 传递给通常的编译器命令行
  • 将选项 -shared 传递给常用的链接器命令行

关于c++ - 能否从 DLL 中动态调用对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17266607/

相关文章:

c# - 从 C# 向 C++ dll 公开 API

c# - 计算 Windows 10 上第 3 方窗口的标题栏按钮的总宽度

c# - 如何将 Char 转换为 .Net 中的 Keycode?

c++ - SendNotifyMessage API 是否跨用户 session 工作?

visual-studio-2008 - 通过 NAnt 与 Visual Studio 构建 - 缺少一个 dll

dll - 升级到 1.1.0 后无法加载文件或程序集 'Microsoft.EntityFrameworkCore.SqlServer, Version=1.1.0.0'

java - 使用 Java 绑定(bind)识别 OpenCV 缺失的 DLL

c++ - 将c++ getline文件输出复制到字符串时的更改

c++ - e1071 中的自定义内核

c++ - C++中接口(interface)文件和实现文件之间的显式函数区别