在 Bash 脚本中调用 C 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3453076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:28:21  来源:igfitidea点击:

Call C function in Bash script

cbash

提问by l0b0

Related to question 3451993, is it possible to call a function which is internal to subst.c (in the Bash source code) in a Bash script?

问题 3451993相关,是否可以在 Bash 脚本中调用 subst.c(在 Bash 源代码中)内部的函数?

采纳答案by Paused until further notice.

Bash supports loadable builtins. You might be able to make use of this to do what you want. See the files in your /usr/share/doc/bash/examples/loadables(or similar) directory.

Bash 支持可加载的内置函数。您也许可以利用它来做您想做的事。查看您/usr/share/doc/bash/examples/loadables(或类似)目录中的文件。

回答by Jay

The simplest way to do this is to write a simple program that collects the input, feeds it to the function, then prints the result. Why don't you tell us what you are attempting to accomplish and perhaps we can suggest an easier way to "skin this cat".

最简单的方法是编写一个简单的程序来收集输入,将其提供给函数,然后打印结果。你为什么不告诉我们你想完成什么,也许我们可以建议一种更简单的方法来“给这只猫剥皮”。

回答by msw

No.

不。

You can't access a function internal to the shell binary from the shell if it is not exported as a shell function.

如果未将其导出为 shell 函数,则无法从 shell 访问 shell 二进制文件内部的函数。

回答by tomlogic

No, you'll have to write a short C program, compile it and call it from the shell.

不,您必须编写一个简短的 C 程序,编译它并从 shell 中调用它。

回答by H_7

This code looks pretty elegant: (from here) Its the same solution @Jay pointed out.

这段代码看起来很优雅:(从这里开始)它与@Jay 指出的解决方案相同。

bash$ cat testing.c 
#include <stdio.h>

char* say_hello()
{
   return "hello world";
}

float calc_xyzzy()
{
     return 6.234;
}

int main(int argc, char** argv)
{
   if (argc>1) {
      if (argv[1][0] =='1') {
        fprintf(stdout,"%s\n",say_hello());
      } else if ( argv[1][0] == '2') {
        fprintf(stdout,"%g\n",calc_xyzzy());
      }
    }
    return 0;
}
bash$ gcc -o testing testing.c 
bash$ ./testing 1
hello world
bash$ ./testing 2
6.234
bash$ var_1="$(./testing 1)"
bash$ var_2="$(./testing 2)"
bash$ echo $var_1
hello world
bash$ echo $var_2
6.234
bash$