lua/python调用C动态库

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

//mylualib.c

#include 
#include 
#include 

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")
print(hi)
#编译命令
gcc -O2 -bundle -undefined dynamic_lookup -o mylualib.so mylualib.c  -I /usr/local/include/

#执行
lua main.lua

python里边相对简洁一些

//mylib.c

#include 

int hello_c(char *str)
{
	printf("output param: %sn", str);
	return 0;
}
# main.py

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

#参数为生成的.so文件所在的绝对路径
libtest = cdll.LoadLibrary(os.getcwd() + '/mylib.so') 

#直接用方法名进行调用
libtest.hello_c("Hello C, I'm calling you from Python") 
#编译命令
gcc -O2 -bundle -undefined dynamic_lookup -o mylib.so mylib.c

#执行
python main.py

Leave a Reply

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

WordPress.com Logo

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

Google photo

You are commenting using your Google 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.