gpt4 book ai didi

c++ - 从 .so 导入函数

转载 作者:行者123 更新时间:2023-11-30 03:26:55 24 4
gpt4 key购买 nike

我需要使用 boost.dll 库从 Linux .so 库中导入一个函数。我的代码是这样的:

namespace n1 {
namespace n2 {
struct st {
std::string n;
int m;
}
}
}

void foo(std::string const&, n1::n2::st& attr) {
/*some implementation*/
}

这里我尝试导入函数foo():

int main(int argc, char** argv) {
boost::filesystem::path path("some path");
boost::dll::experimental::smart_library lib(path);
auto f2 = lib.get_function<void(std::string const&, n1::n2::st&)>(path, "n1::n2::foo"); //<<----here runtime error
f2( std::string(), st{});
}

但是我得到这个运行时错误:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl >' what(): boost::dll::shared_library::get() failed (dlerror system message: /path_to_my_library.so: undefined symbol: n1::n2::foo): Illegal seek

最佳答案

因为 n1::n2::foo 不是 C 兼容的导出名称,我建议您需要使用损坏的名称,或者使用 mangled_import

Caution: This feature is experimental

在我的编译器上

foo(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, n1::n2::st&)

破坏到

_Z3fooRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERN2n12n22stE

关于同时导入结构的主题,请参阅 Class Imports

更新

基于手动处理方法的工作示例:

  1. 共享.cpp

    #include "shared.h"
    #include <iostream>

    void foo(std::string const& msg, n1::n2::st& attr) {
    std::cout << msg << " from " << __FILE__ << ":" << __LINE__ << " (" << __PRETTY_FUNCTION__ << ")\n";
    std::cout << "attr.m = " << attr.m << "\n";
    std::cout << "attr.n = " << attr.n << "\n";
    }
  2. 共享.h

    #include <string>
    namespace n1 { namespace n2 { struct st { std::string n; int m; }; } }
  3. main.cpp

    #include <boost/dll.hpp>
    #include <boost/dll/smart_library.hpp>
    #include <boost/dll/import_mangled.hpp>
    #include <boost/exception/diagnostic_information.hpp>
    #include <iostream>

    #include "shared.h"

    int main() {
    boost::filesystem::path path("./libshared.so");
    try {
    boost::dll::experimental::smart_library lib(path);
    //auto f1 = boost::dll::experimental::import_mangled<void(std::string const&, n1::n2::st&)>(path, "foo");
    auto f1 = boost::dll::import<void(std::string const&, n1::n2::st&)>(path, "_Z3fooRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERN2n12n22stE");

    n1::n2::st arg { "world", 42 };
    f1("hello", arg);

    } catch(boost::exception const& e) {
    std::cout << boost::diagnostic_information(e, true) << '\n';
    }
    }

查看 Live On Coliru

编译:

g++ -std=c++14 -shared -fPIC shared.cpp -o libshared.so
g++ -std=c++14 main.cpp -ldl -lboost_system -lboost_filesystem

显示错位的名称

nm libshared.so

运行演示
./a.out

打印

hello from shared.cpp:5 (void foo(const string&, n1::n2::st&))
attr.m = 42
attr.n = world

关于c++ - 从 .so 导入函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47832593/

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