Chinaunix首页 | 论坛 | 博客
  • 博客访问: 56735
  • 博文数量: 13
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 130
  • 用 户 组: 普通用户
  • 注册时间: 2015-04-26 15:04
文章分类

全部博文(13)

文章存档

2015年(13)

我的朋友

分类: LINUX

2015-05-22 23:23:14

  最基本的面向对象,应该就是在调用函数的时候,能自动传入this指针。
  lua用":"操作符实现了这一点,c语言要想这么做,估计也是不费吹灰之力,但c的编译器作者大概不会这么干。
  所以,用面向对象的方式,来操作c的结构体,调用c的函数,其实就是借了lua的一个":"操作符而已。当然,在技术层面,还是靠metatable的支持。
  太晚了,就不写了,把代码贴上来。以后考虑这个wrapper.c能否自动生成,这样,就能写个工具,把既有项目的c对象和围绕它的方法导出来。智能的oop封装。
  不知道c++又怎样。
dog.h

点击(此处)折叠或打开

  1. struct dog{
  2.     int age;
  3. };
  4. void set_age(struct dog *dog, int age);
  5. int get_age(struct dog *dog);

dog.c

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<dog.h>

  3. void set_age(struct dog *dog, int age){
  4.     dog->age = age;    
  5. }
  6. int get_age(struct dog *dog){
  7.     return dog->age;
  8. }


wrapper.c

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<lua.h>
  3. #include<lualib.h>
  4. #include<dog.h>


  5. /* 在lua里,我当然想写成dog:set_age(123)这样,也就是set_age(dog, 123)这样。
  6.  * 于是知道在c里怎么写了。
  7.  */
  8. int _set_age(lua_State *L){
  9.     struct dog * arg_dog = lua_touserdata(L, -2);
  10.     int arg_age = lua_tointeger(L, -1);

  11.     set_age(arg_dog, arg_age);

  12.     return 0;
  13. }

  14. int _get_age(lua_State *L){
  15.     struct dog *arg_dog = lua_touserdata(L, -1);

  16.     int age = get_age(arg_dog);
  17.     lua_pushinteger(L, age);

  18.     return 1;
  19. }

  20. /*prototype: userdata createDog(void)*/
  21. int createDog(lua_State *L){
  22.     struct dog *dog = lua_newuserdata(L, sizeof(struct dog));

  23.     luaL_newmetatable(L, "metatable");
  24.     lua_pushstring(L, "__index");
  25.     lua_pushvalue(L, -2);
  26.     lua_settable(L, -3);
  27.     /**---*/
  28.     lua_pushstring(L, "get_age");
  29.     lua_pushcfunction(L, _get_age);
  30.     lua_settable(L, -3);
  31.     /*----*/
  32.     lua_pushstring(L, "set_age");
  33.     lua_pushcfunction(L, _set_age);
  34.     lua_settable(L, -3);

  35.     lua_setmetatable(L, -2);

  36.     return 1;
  37. }

  38. int luaopen_cmodule(lua_State *L){
  39. /*    lua_register(L, "set_age", _set_age);*/
  40. /*    lua_register(L, "get_age", _get_age);*/
  41.     lua_register(L, "createDog", createDog);
  42.     return 0;
  43. }
 gcc -o module.so dog.c wrapper.c -shared -llua -L../ -I../ -I./

点击(此处)折叠或打开

  1. wws@ubuntu:~/Downloads/lua-5.1/src/test$ lua
  2. Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
  3. > require"cmodule"
  4. > dog=createDog()
  5. > dog:set_age(1)
  6. > print(dog:get_age())
  7. 1
  8. > dog:set_age(3)
  9. > print(dog:get_age())
  10. 3




阅读(1493) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~