开发者

Call C function in Bash script

Related to question 3451993, is it pos开发者_运维知识库sible to call a function which is internal to subst.c (in the Bash source code) in a Bash script?


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.


It even possible to use C data structures ;)

This is ctypes.sh, a foreign function interface for bash. ctypes.sh is a bash plugin that provides a foreign function interface directly in your shell. In other words, it allows you to call routines in shared libraries from within bash.

Check out https://github.com/taviso/ctypes.sh ;)


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".


No.

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


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


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

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$
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜