在读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;
}