gpt4 book ai didi

c++ - *.so 使用来自其他 *.so 的函数时如何使用 dlopen 和 dlsym

转载 作者:太空宇宙 更新时间:2023-11-04 03:40:11 24 4
gpt4 key购买 nike

我有以下使用 dlopen 和 dlsym 的代码。

主要.cpp

#include <stdio.h>
#include <dlfcn.h>
int main(int argc,char** argv) {
void* handler;
handler = dlopen("./libsql.so",RTLD_LAZY);
if(handler){
int (*insert)(const char*);
char* error=NULL;

dlerror(); /* Clear any existing error */

*(void **) (&insert) = dlsym(handler, "openAndInsert");
if ((error = dlerror()) == NULL) {
(*insert)(argv[1]);
}
else {
printf("Error in dlsym\n");
}
}
else {
printf("dlopen error\n");
}
return 0;
}

编译命令:g++ main.cpp -ldl

libsql.cpp

#include <sqlite3.h>
#include <string.h>
#include <stdio.h>
#include "libsql.h"

int openAndInsert(const char* sql) {
sqlite3 *db;
sqlite3_stmt *stmt;
sqlite3_initialize();
int rc = sqlite3_open("./database.db", &db);
if(rc==0){
rc = sqlite3_prepare(db, sql, strlen(sql), &stmt, NULL);
if(rc==0) {
if(sqlite3_step(stmt)){
printf("Done\n");
}
else {
printf("execute error\n");
}
sqlite3_finalize(stmt);
}
else {
printf("prepare error\n");
}
sqlite3_close(db);
}
else {
printf("open error\n");
}
sqlite3_shutdown();
}

libsql.h

#ifndef LIBSQL_H_
#define LIBSQL_H_
#ifdef __cplusplus
extern "C" {
#endif

int openAndInsert(const char* sql);
#ifdef __cplusplus
}
#endif

#endif

编译命令:g++ -fPIC -shared -o libsql.so libsql.cpp

现在,当我运行应用程序时,出现如下错误。

./a.out: symbol lookup error: ./libsql.so: undefined symbol: sqlite3_initialize

但是 libsqlite3 已经安装并且可以与其他程序一起正常工作。

最佳答案

当我使用下面的命令生成我的 *.so 文件时,它工作正常。

g++ -fPIC -shared -o libsql.so libsql.cpp -lsqlite3

关于c++ - *.so 使用来自其他 *.so 的函数时如何使用 dlopen 和 dlsym,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29346939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com