使用方法:
1,先創建一個xxx.c文件,寫入下面代碼
#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
unsigned char crc8(const unsigned char *ptr,unsigned char len)
{
unsigned char i;
unsigned char crc = 0;
while(len--!=0)
{
for(i = 1; i != 0; i *= 2){
if((crc & 1) != 0){
crc /= 2;
crc ^= 0x8C;
}else{
crc /= 2;
}
if((*ptr & i) != 0){
crc ^= 0x8C;
}
}
ptr++;
}
return (crc);
}
int CRC8(lua_State *L)
{
int i = 0;
const unsigned char *str = luaL_checkstring(L,1);/*取出LUA調用CRC8函數時傳遞的第2個參數*/
int len = luaL_checknumber(L,2);/*取出LUA調用CRC8函數時傳遞的第2個參數*/
unsigned char ret = crc8(str,len);
lua_pushnumber(L,ret);/*CRC8函數在LUA中的返回值*/
return 1;
}
static luaL_Reg crclibs[] = {
{"CRC8",CRC8}, /*此處就是提供給LUA調用的函數數組,用於luaL_setfuncs()函數註冊*/
{NULL,NULL}
};
int luaopen_libcrc(lua_State* L)
{
/*步驟2生成的動態庫的名稱 要和 "luaopen_libcrc" 中 "libcrc" 這幾個字符一樣,不然會報錯*/
lua_newtable(L);
/*註冊數組crclibs 中的所有函數*/
luaL_setfuncs(L,crclibs,0);
return 1;
}
2,編譯上面代碼生成lua使用的動態庫
gcc -fPIC -shared xxx.c -o libcrc.so
3,測試使用該庫
local mylib = require("libcrc")
local cmd = {0x55,0xAA,0x04,0x05}
local str = ""
local len = #cmd --表cmd的長度
for i=1,len do
str = str..string.format("%c",cmd[i])
end
local crc = mylib.crc8(str,len) --由於未找到lua傳遞表到C 的函數,所以這裏採用傳遞了字符串