Step by step (LUA calls the C function)

Source: Internet
Author: User

Lua's ability to call C functions greatly improves Lua's scalability and availability. For some functions related to the operating system or modules with high efficiency requirements, we can use the C function, and then call the specified C function through Lua. For the C functions that can be called by Lua, the interface must follow the Lua requirement, that isTypedef int (* lua_cfunction) (lua_state * l). This function type only contains a pointer indicating the Lua environment as its unique parameter. The implementer can use this pointer to further obtain the LuaCode. The return value is an integer, indicating the number of values that the C function will return to Lua code. If no value is returned, return 0. It should be noted that the C function cannot directly return the real return value to the Lua code, but transmits the call parameters and return values between the Lua code and the C function through the Virtual stack. Here we will introduce two Lua rules for Calling C functions.
1. c Functions as applicationsProgram.

 1 # Include <stdio. h> 2 # Include < String . H> 3 # Include <Lua. HPP>4 # Include <lauxlib. h> 5 # Include <lualib. h> 6   7   //  The C registration function to be called by Lua.  8   Static   Int Add2 (lua_state * L)  9   {  10       //  Check whether the parameters in the stack are valid. 1 indicates the first parameter (from left to right) for Lua calling, and so on. 11       //  If the parameter passed by the Lua code during the call is not a number, this function will report an error and terminate the program execution.  12       Double OP1 = lual_checknumber (L, 1  );  13       Double OP2 = lual_checknumber (L, 2  );  14       //  Push the function result into the stack. If there are multiple return values, you can press them into the Stack multiple times.  15 Lua_pushnumber (L, OP1 +OP2 );  16       //  The return value is used to indicate the number of returned values of the C function, that is, the number of returned values pushed into the stack.  17       Return   1  ;  18   }  19   20   //  Another C registration function to be called by Lua.  21   Static   Int Sub2 (lua_state *L)  22   {  23       Double OP1 = lual_checknumber (L, 1  );  24       Double OP2 = lual_checknumber (L, 2  );  25 Lua_pushnumber (L, OP1- OP2 );  26       Return   1 ;  27   }  28   29   Const   Char * Testfunc = "  Print (Add2 (1.0, 2.0) print (sub2 (20.1, 19 ))  "  ;  30   31   Int  Main ()  32   { 33 Lua_state * l = Lual_newstate ();  34   Lual_openlibs (L );  35       //  Register the specified function as a global function variable of Lua. The first string parameter is the Lua code.  36       //  The global function name used to call the C function. The second parameter is the pointer of the actual C function.  37 Lua_register (L, "  Add2  "  , Add2 ); 38 Lua_register (L, "  Sub2  "  , Sub2 );  39       //  After registering all the C functions, you can use these registered c Functions in the Lua code block.  40       If  (Lual_dostring (L, testfunc ))  41 Printf ( "  Failed to invoke. \ n  "  ); 42   Lua_close (L );  43       Return   0  ;  44 }

2. The C function library becomes the Lua module.
Copy the library files containing C functions, such as Linux So or Windows DLL, to the current directory where the Lua code is located, or to the directory pointed to by the lua_cpath environment variable, so that the Lua parser can locate them correctly. In my current Windows system, I copied it to "C: \ Program Files \ Lua \ 5.1 \ clibs \", which contains all the C libraries that Lua can call. See the following C language code and key notes:

 1 # Include <stdio. h> 2 # Include < String . H>3 # Include <Lua. HPP> 4 # Include <lauxlib. h> 5 # Include <lualib. h> 6   7   //  The Declaration Form of the C function to be registered has been given in the above example.  8   //  It must be noted that the function must be exported in the form of C, so extern "C" is required.  9   //  The function code is the same as in the previous example.  10   Extern  "  C  "   Int Add (lua_state * L)  11   {  12       Double OP1 = lual_checknumber (L, 1  );  13       Double OP2 = lual_checknumber (L, 2  );  14 Lua_pushnumber (L, OP1 + OP2 );  15       Return   1  ;  16   }  17   18   Extern   "  C  "   Int Sub (lua_state * L)  19   { 20       Double OP1 = lual_checknumber (L, 1  );  21       Double OP2 = lual_checknumber (L, 2  );  22 Lua_pushnumber (L, OP1- OP2 );  23       Return   1  ;  24   } 25   26   //  The first field of the lual_reg struct is a string, which is used to notify Lua of the name of the function during registration.  27   //  The first field is the c function pointer.  28   //  The two fields of the last element in the struct array are null, prompting that the Lua registration function has reached the end of the array.  29   Static Lual_reg mylibs [] = {  30 { " Add  "  , Add },  31 { "  Sub  "  , Sub },  32   {Null, null}  33   };  34   35   //  The unique entry function of the C library. The function signature is equivalent to the above registered function. See the following description:  36  //  1. We can simply understand this function as a module's factory function.  37   //  2. The function name must be luaopen_xxx. xxx indicates the library name. The Lua Code require "XXX" needs to correspond to it.  38   //  3. In the lual_register call, the first string parameter is the module name "XXX", and the second parameter is the array of the function to be registered.  39   //  4. It should be emphasized that all codes that require "XXX" must be consistent, regardless of C or Lua. This is the agreement of Lua,  40   //  Otherwise, it cannot be called.  41  Extern   "  C  "  _ Declspec (dllexport)  42   Int Luaopen_mytestlib (lua_state * L)  43   {  44       Const   Char * Libname = "  Mytestlib  " ;  45   Lual_register (L, libname, mylibs );  46       Return   1  ;  47 }

See the following Lua code:

  1   require  "   mytestlib  "   --   specify the package name   2   3   --   the package must be used during the call. function   4   Print  (mytestlib. add ( 1.0 ,  2.0  )   5   Print  (mytestlib. sub ( 20.1 ,  19  )) 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.