用boost操作动态库

·

boost从1.61版本开始实现了跨平台操作动态库的代码。

#include <boost/dll.hpp>

int main(int argc, char *argv[])
{
	//方法1
	auto cpp11_func = boost::dll::import<int __stdcall(int)> (
		"test.dll", "TestFunction"
	);
	//调用函数
	cpp11_func(1);
	//方法2
	boost::dll::shared_library dll;
	dll.load("test.dll");
	if (dll.is_loaded() == false)
		return -1;
	auto symbol = dll.get<int __stdcall(int)>("TestFunction");
	if (symbol == nullptr) {
		dll.unload();
		return -2;
	}
	//调用函数
	symbol(2);
	dll.unload();
	//注意:dll在析构的时候会释放DLL
	//方法3
	auto p = boost::dll::import<void()>(lib_path, "test_function_name");
	p();
	//p为share_ptr,引用计数为0后同样会释放DLL
	return 0;
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注