动态加载动态库(windows/linux)

在读TNN/MACE代码时总看到动态加载相关代码,因此在这做一个总结和试用。代码参考windows动态加载linux动态加载

通过dlsym/getprocaddress获取动态库的函数地址,然后利用该地址进行其它相关操作(重命名函数之类的)。

#ifdef WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include "CL/cl.h"

typedef CL_API_ENTRY cl_int(CL_API_CALL *clGetPlatformIDsFuncPtr)(
	cl_uint          /* num_entries */,
	cl_platform_id * /* platforms */,
	cl_uint *        /* num_platforms */) CL_API_SUFFIX__VERSION_1_0;
typedef CL_API_ENTRY cl_int(CL_API_CALL *clGetPlatformInfoFuncPtr)(
	cl_platform_id   /* platform */,
	cl_platform_info /* param_name */,
	size_t           /* param_value_size */,
	void *           /* param_value */,
	size_t *         /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0;
static clGetPlatformIDsFuncPtr clGetPlatformIDsPtr = NULL;
static clGetPlatformInfoFuncPtr clGetPlatformInfoPtr = NULL;

#define clGetPlatformInfo clGetPlatformInfo_Test
cl_int CL_API_CALL clGetPlatformInfo_Test(
	cl_platform_id   platform,
	cl_platform_info param_name,
	size_t           param_value_size,
	void             *param_value,
	size_t           *param_value_size_ret)
{
	return (clGetPlatformInfoPtr)(platform, param_name, param_value_size, param_value, param_value_size_ret);
}
int main()
{
#ifdef WIN32
	HINSTANCE ocl_lib = LoadLibrary(TEXT("opencl.dll"));
	if (!ocl_lib)
	{
		printf("Load Library failed\n");
	}
	clGetPlatformIDsPtr = (clGetPlatformIDsFuncPtr)(GetProcAddress(ocl_lib, "clGetPlatformIDs"));
	clGetPlatformInfoPtr = (clGetPlatformInfoFuncPtr)(GetProcAddress(ocl_lib, "clGetPlatformInfo"));
#else
	void* ocl_lib = dlopen("libOpenCL.so", RTLD_NOW);
	if (!ocl_lib)
	{
		printf("Load Library failed\n");
	}
	clGetPlatformIDsPtr = (clGetPlatformIDsFuncPtr)(dlsym(ocl_lib, "clGetPlatformIDs"));
	clGetPlatformInfoPtr = (clGetPlatformInfoFuncPtr)(dlsym(ocl_lib, "clGetPlatformInfo"));
#endif

	unsigned int num = 0;
	int iRslt = clGetPlatformIDsPtr(0, NULL, &num);

	cl_platform_id* platform_id = (cl_platform_id*)malloc(num * sizeof(cl_platform_id));

	iRslt = clGetPlatformIDsPtr(num, platform_id, NULL);

	cl_platform_id cl_platform = platform_id[0];
	free(platform_id);
	char platname[50];
	clGetPlatformInfo(cl_platform, CL_PLATFORM_NAME, 50 * sizeof(char),
		platname, NULL);
#ifdef WIN32
	FreeLibrary(ocl_lib);
#else
	dlclose(ocl_lib);
#endif
	printf("%s\n", platname);
	return iRslt;
}

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值