⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 call_math.cpp

📁 斯坦福Energy211/CME211课《c++编程——地球科学科学家和工程师》的课件
💻 CPP
字号:
// This program demonstrates loading dynamic libraries// programmatically, and calling their functions// To compile this program://// g++ call_math.cpp -ldl//// where the -ldl option tells the linker to include the// library /lib/libdl.so, which includes the functions// dlopen and dlsym#include <dlfcn.h>#include <iostream>using namespace std;typedef double (*functype)(double);int main() {    // /lib/libm.so is the C standard math library    // Use dlopen to load it into memory.  RTLD_LAZY    // means only resolve references to functions in    // the library as they are needed, instead of    // resolving all of them at once, which is wasteful    // if most functions in the library won't be used.    // Note that the path to the library is not included,    // because dlopen will look in standard directories    void *plib = dlopen( "libm.so", RTLD_LAZY );    if ( plib == NULL ) {        // Library could not be found, abort        cerr << "Could not open math library\n";         return 1;    }    do {        // Get the name of a function to call        cout << "Enter the name of the function you would like to call,\n";        cout << "or enter END to quit: ";        string s;        cin >> s;        if ( s == "END" )            break;                // Look up the function in the library        void *psym = dlsym( plib, s.c_str() );        if ( psym == NULL )            cerr << "Function not found\n";        else {            // We assume the function takes a single argument, a double,            // and returns a double            cout << "Enter x-value: ";            double x;            cin >> x;            // functype is a type that represents a pointer to a function            // that takes a double argument returns a double.  dlsym            // returns a generic pointer to void, so we have to convert            // before we can call the function            functype pfunc = (functype) psym;            // Now call the function and obtain the return value            double y = pfunc(x);            cout << s << "(" << x << ") = " << y << endl;        }    } while ( true );    return 0;}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -