如何在C ++中加载共享对象? [英] How do I load a shared object in C++?

查看:121
本文介绍了如何在C ++中加载共享对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个共享对象(一个所谓的Linux等效的Windows DLL),我想导入和使用我的测试代码。

I have a shared object (a so - the Linux equivalent of a Windows dll) that I'd like to import and use with my test code.

我相信这不是这么简单;)但这是我想做的事情。

I'm sure it's not this simple ;) but this is the sort of thing I'd like to do..

#include "headerforClassFromBlah.h"

int main()
{
    load( "blah.so" );

    ClassFromBlah a;
    a.DoSomething();
}



我假设这是一个非常基本的问题,

I assume that this is a really basic question but I can't find anything that jumps out at me searching the web.

推荐答案

在C ++中加载共享对象有两种方式

There are two ways of loading shared objects in C++

对于任何一种方法,你总是需要你想使用的对象的头文件。

For either of these methods you would always need the header file for the object you want to use. The header will contain the definitions of the classes or objects you want to use in your code.

静态:

#include "blah.h"
int main()
{
  ClassFromBlah a;
  a.DoSomething();
}

gcc yourfile.cpp -lblah

动态在Linux中):

Dynamically (In Linux):

#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main(int argc, char **argv) {
    void *handle;
    double (*cosine)(double);
    char *error;
    handle = dlopen ("libm.so", RTLD_LAZY);
    if (!handle) {
        fprintf (stderr, "%s\n", dlerror());
        exit(1);
    }
    dlerror();    /* Clear any existing error */
    cosine = dlsym(handle, "cos");
    if ((error = dlerror()) != NULL)  {
        fprintf (stderr, "%s\n", error);
        exit(1);
    }
    printf ("%f\n", (*cosine)(2.0));
    dlclose(handle);
    return 0;
}

*从 dlopen Linux手册页
在Windows或任何其他平台下的过程是一样的,只需用平台版本的动态符号搜索替换dlopen。

*Stolen from dlopen Linux man page The process under windows or any other platform is the same, just replace dlopen with the platforms version of dynamic symbol searching.

要使动态方法生效,要导入/导出的所有符号必须具有extern的C链接。

For the dynamic method to work, all symbols you want to import/export must have extern'd C linkage.

有一些词关于何时使用静态和何时使用动态链接。

There are some words Here about when to use static and when to use dynamic linking.

这篇关于如何在C ++中加载共享对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆