使用lua编写游戏程序,往往使用c 或者 c++ 编写游戏引擎,那么就需要在lua中调用动态链接库,脚本语言写逻辑比低级语言方便。



static int hello_c (lua_State *L) {
    const char * from_lua = lua_tostring(L,1);
    printf("Lua: %sn",from_lua);    
    lua_pushstring(L,"Hi Lua, nice to meet you");
    return 1;
static const struct luaL_Reg mylualib [] = {
    {"hello_c", hello_c},
    {NULL, NULL} /* sentinel */
int luaopen_mylualib (lua_State *L) {
    luaL_newlib(L, mylualib);     /* register a array of c functions exported to lua */
    lua_pushvalue(L, -1);
    lua_setglobal(L, "mylualib"); /* the module name */

    return 1;
# main.lua 

require "mylualib"
hi = mylualib.hello_c("Hi C, I'm Lua")
gcc -O2 -bundle -undefined dynamic_lookup -o mylualib.c  -I /usr/local/include/

lua main.lua




int hello_c(char *str)
	printf("output param: %sn", str);
	return 0;

#coding: utf-8
from ctypes import *
import os 

libtest = cdll.LoadLibrary(os.getcwd() + '/') 

libtest.hello_c("Hello C, I'm calling you from Python") 
gcc -O2 -bundle -undefined dynamic_lookup -o mylib.c


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.