[Lua] LUA calls C/C + + functions/libraries (dynamic link mode)

Source: Internet
Author: User
Tags cos lua sin

New DLL empty Win32 project, new Test.cpp file, the content is as follows

/*lua call C + + functions/libraries (dynamic link mode) */#include <iostream>using namespace std; #include <lua.hpp>static int Math_abs ( Lua_state *l) {    lua_pushnumber (L, ABS ((int) Lual_checknumber (l, 1)));    return 1;} static int Math_cos (Lua_state *l) {    lua_pushnumber (l, cos ((double) Lual_checknumber (L, 1)));    return 1;} static int Math_sin (Lua_state *l) {    lua_pushnumber (l, sin (double) lual_checknumber (L, 1));    return 1;}  static const Lual_reg Mathlib[] = {{"    abs", Math_abs},    {"cos", Math_cos}, {    "sin", math_sin},    {NULL, NULL}};//dll is exported through the function Luai_openlib, and LUA uses the Package.loadlib import library function extern "C" __declspec (dllexport) int Luaapidll (lua_state * L)//Where attention is required, this function is named consistent with the library name {    luai_openlib (L, "Dy_math", mathlib,0);    return 1;}


Lualoadlib.lua file
--region lualoadlib.lualocal libpath= "./. /debug/luaapidll.dll "Local loadlibfunc=package.loadlib (Libpath," Luaapidll ") Loadlibfunc () function COS (a)    Print ("Called COS in Lua script")    return Dy_math.cos (a) endfunction sin (a)    print ("called SIN in Lua script")    Return Dy_math.sin (a) EndPrint (COS (60*3.1415926/180)) print (sin ()) os.execute ("pause")--double-click the file directly, The cmd window does not disappear--endregion

Double-click the Lualoadlib.lua file directly and the result is as follows


[Lua] LUA calls C/C + + functions/libraries (dynamic link mode)

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.