c++中使用dlopen加载动态库中带类参数的函数

说明

我一直都知道dlopen的大概用法。但是dlopen毕竟是c语言的函数,能否加载带c++类型传参的函数,我有点不确定。今天有空验证了下,是可以的。extern “C”只影响了函数在动态库中的Name Mangling,并不排斥参数和回参使用c++类型。

一个例子

test.h
#include <string>

extern "C" std::string*  test(std::string info);

//定义函数指针类型名为test_t
using test_t =  std::string*  (*)(std::string info);
test.cpp
#include <string>
#include <stdio.h>

#include "test.h"

static std::string g_str("this is test");

std::string*  test(std::string info)
{
	printf("in test:%s\n", info.c_str());
	return &g_str;
}

main.cpp
#include <stdio.h>
#include <string>

#include <iostream>
#include <dlfcn.h>

#include "test.h"

int  main()
{
	void* handle = dlopen("./libtest.so", RTLD_LAZY);
	if (!handle) {
		printf("Cannot open library");
		return 1;
	}

	// reset errors
	test_t testfunc = reinterpret_cast<test_t>(dlsym(handle, "test"));
	if (test == nullptr) {
		printf("Cannot load symbol 'test'\n");
		dlclose(handle);
		return 1;
	}

	// use it to do the calculation
	printf("Calling test...\n");

	auto p = testfunc("this is main");
	printf("get info:%s\n", p->c_str());
	return 0;
}


mk.sh
#!/bin/sh
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:./
gcc test.cpp -fPIC   -shared -std=c++11  -o libtest.so
gcc main.cpp  -L./ -ltest -ldl -lstdc++ -std=c++11  -o main

执行结果

代码比较 简单,一目了然。

Calling test...
in test:this is main
get info:this is test

参考资料

linux下C++动态链接C++库示例详解

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值