c++ DLL导出类和导出函数

一、导出函数

背景:

导出函数: 在DLL中有一张导出表,其中有一系列函数,这些函数叫做导出函数。这些函数可供外部程序调用,即这些函数都是该DLL的入口点(类似main函数)。不在导出表中的函数,为该DLL私有的函数,外部程序不能调用它们。

1、没有__declspec(dllexport),将生成的测试lib库添加到项目中,直接调用,会报错:

LNK2019	无法解析的外部符号 "void __cdecl test(void)" (?test@@YAXXZ),该符号在函数 main 中被引用
LNK1120	1 个无法解析的外部命令

2、正确写法:.h文件

#ifdef TESTDLLEXPORT
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT __declspec(dllimport)
#endif

#ifdef __cplusplus
extern "C" {
#endif

DLLEXPORT void test();

#ifdef __cplusplus
}
#endif

二、导出类

只需要在class后加上_declspec(dllexport)即可实现导出类。

1、与导出函数类似,不加_declspec,会报错LNK2019

2、正确写法:.h文件

#pragma once
class _declspec(dllexport) exportClass
{
public:
	exportClass(int a);
	~exportClass();

	void testexportclass();

private:
	int m_a;
};

.cpp文件

#include "exportClass.h"
#include <iostream>
using namespace std;

exportClass::exportClass(int a) {
	m_a = a;
}

exportClass::~exportClass() {
	cout << "export class destructure" << endl;
}

void exportClass::testexportclass() {
	cout << m_a << "+++++test export class!" << endl;
}

测试程序

#include "exportfun.h"
#include "exportClass.h"
#include <iostream>

int main()
{
	exportClass stu(666);
	stu.testexportclass();
	testexportfun();
	system("pause");
	return 1;
}

输出结果:

  • 8
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Python DLL 是通过使用 ctypes 或 cffi 等模块来调用在 C 或 C++ 中编写的动态链接库。而在 Python DLL导出,可以作为一个模块调用或者在其他 Python 脚本中实例化使用。 在 C 或者 C++ 中,我们可以使用导出函数的方式来将导出DLL 中的函数。在 Python 中,我们可以使用 ctypes 模块来加载 DLL,并且使用函数指针方式来访问导出。 首先,我们需要得到 DLL 文件的路径,并使用 ctypes 的 cdll 或者 WinDLL 函数加载 DLL。然后,使用 ctypes 的 POINTER 函数来创建指向的指针型。接着,我们可以使用 getattr 函数来获取 DLL导出函数,并将其转换为 Python 中的函数。最后,我们使用指针来实例化导出,并调用其中的方法。 以下是一个示例代码: ```python import ctypes # 加载 DLLdll = ctypes.WinDLL('example.dll') # 创建指向的指针型 ClassPtr = ctypes.POINTER(ctypes.c_void_p) # 获取 DLL导出函数 get_class = getattr(dll, 'get_class') get_class.restype = ClassPtr # 实例化导出 c = get_class() # 调用中的方法 # 假设导出中有一个名为 foo 的函数 foo = getattr(dll, 'foo') foo.argtypes = [ClassPtr] foo.restype = ctypes.c_void_p result = foo(c) ``` 通过以上方法,我们就能够在 Python 中调用通过 DLL 导出了。当然,在实际应用中,我们需要根据实际情况进行相应的参数配置和错误处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值