Write Lua extensions so files and invoke method instances under Linux

Source: Internet
Author: User
Tags lua

This article mainly introduced under Linux to write LUA extensions so file and Invoke method instance, this article gives the C language code, compile so file, Lua call code instance, need friends can refer to the following

The code is as follows:

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include "Lua.h"

#include "Lualib.h"

#include "Lauxlib.h"

/* The front declaration of the open function of the library * *

int Luaopen_mylib (lua_state *l);

static int L_sin (Lua_state *l)

{

Double d = Lual_checknumber (L, 1);

Lua_pushnumber (L, sin (d));

printf ("OK now luahook!n");

return 1; /* Number of results * *

}

static const Lual_reg mylib[] =

{

{"Lsin", L_sin},

{NULL, NULL}/* must end with NULL/*

};

int Luaopen_mylib (lua_state *l)

{

Luai_openlib (L, "Mylib", Mylib, 0);

return 1;

}

If you are a. cpp file, be sure to add extern "C" to the Luaopen_mylib, or the exported function will be renamed, remember

Compiling: gcc mylibs.c-fpic-shared-o Libmylib.so-llua

The code is as follows:

Makefile file

CXX =GCC

Libname:=libmylib.so

Hdrname:=mylibs.c

Targetname:=mylibs

cname:=$ (Patsubst%,%.c,$ (TARGETNAME))

oname:=$ (Patsubst%,%.o,$ (TARGETNAME))

All:libmylib

Libmylib: $ (oname)

$ (CXX)-g-shared-wl,$ (libname)

-O $ (libname) $ (oname)-llua

%.O:%.c

$ (CXX)-fpic-c-wall $ (CNAME) clean:$ (RM) *.o *.so

Lua invokes the script:

The code is as follows:

Local one, two, three = Package.loadlib ("libmylib.so", "Luaopen_mylib") ()

Print (Mylib.lsin (10))

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.