hunhun1981的专栏

移动开发,二维码,J2ME,Android,BlackBerry,iPhone,Symbian,Windows Mobile,Sun SPOT

用户操作
[即时聊天] [发私信] [加为好友]
张宇ID:hunhun1981
28414次访问,排名4164好友25人,关注者27
程序员
hunhun1981的文章
原创 53 篇
翻译 0 篇
转载 39 篇
评论 33 篇
张宇的公告
邮件订阅hunhun1981的专栏 加入我的维信
最近评论
zijingwuhaolou:很好很强大
zijingwuhaolou:很好很强大
Tirtle:確定大文件Jpeg file這個decoder能decode嗎?

我當初就是會解不了所以才頭痛
最後是靠著把org.eclipse.internal.image.JPEGDecoder這個decoder挖出來用才解決的
而且這個decoder也剛好是直接數據流解碼, 產生Image

最近遇到一個問題讓我煩
就是很多Wi……
hunhun1981:谢谢你的回复。
不过使用这个解码器,是为了能够对大文件(1280x1024以上)进行二维码的图形解码。这样的尺寸在多数手机没法构造。所以我们准备修改解码算法,直接在数据流中实现二维码的解码。
因此,才需要一个轻量级的图像解码器。

不过,到现在还没做完,呵呵!
Tirtle:其實很多手機上的Java platform都可以直接解JPEG了
只有某些較舊的機種或Java platform解不了
當使用內建的Decoder失敗時再改用軟體解即可

文章中提到的這個Decoder解大多數JPEG都沒問題
但是解某些Mega-Pixel JPEG時會出錯
會解出很奇怪的結果
文章分类
收藏
    相册
    朋友
    inc143的测试专栏
    mengya810104的测试专栏
    抛砖引砖--程老师
    暗夜公爵-游戏设计
    蓝天里的星星象钻石
    其它
    混混的淘宝店铺
    零余者环保资讯
    存档
    软件项目交易
    订阅我的博客
    XML聚合  FeedSky
    订阅到鲜果
    订阅到Google
    订阅到抓虾
    订阅到BlogLines
    订阅到Yahoo
    订阅到GouGou
    订阅到飞鸽
    订阅到Rojo
    订阅到newsgator
    订阅到netvibes

    转载 Using Lua with C#收藏

    新一篇: SCSL,J2ME源代码 | 旧一篇: lua 5.0的实现(翻译)1,2,3,4,5部分


    by Martin Echenique

    Using Lua with C#

    When developing large software projects, one of the main time consuming tasks is building the program over and over. Modern day compilers and hardware try to be smarter and faster and minimize that as much as they possibly can, but being honest, we still spend quite a lot of time staring blankly at the screen between builds. To cope with that problem, we've seen an increasing trend of embedding lightweight interpreted languages that allow us to easily and quickly change pieces of code and see what happens instantly, instead of waiting for another dreadful build cycle. Two of the most common choices are Python and Lua, because the way the languages are designed and implemented makes it quite easy to embed them in other applications. Also, they provide a simpler interface for the less technically talented people to write new features without having to learn something as daunting as C++ or pester one of the programmers to code in the idea.

    For this "tutorial" we're going to work with C# and the LuaInterface assembly. You can find them over at MSDN (get the .NET 1.1 framework SDK) and luaForge (version 1.3.0 at the moment). Newer versions should work just fine as soon as they come out.

    Embedding Lua into C# with LuaInterface is so easy that it's almost embarrassing. The wrapper takes care of most everything and exposes a very easy to work with API. To start with it right away, we could try this:

     
    using System;
    using LuaInterface;

    namespace LuaCon
    {
       
    class Program
       {
          
    private bool bRunning = true;
          
    public static Lua pLuaVM = null;

          
    public Program()
          {
             pLuaVM 
    = new Lua();
          }

          
    static void Main(string[] args)
          {
             Program pPrg 
    = new Program();
             pPrg.Run();
          }

          
    public void Run()
          {
             String strInput;

             
    while (bRunning)
             {
                Console.Write(
    "");

                strInput 
    = Console.ReadLine();
                
    if (strInput == "quit")
                   bRunning 
    = false;
                
    else
                {
                   Console.WriteLine();
                   
    try
                   {
                      pLuaVM.DoString(strInput);
                   }
                   
                   
    catch (Exception ex)
                   {
                      Console.WriteLine(ex.Message);
                   }

                   
    finally
                   {
                      Console.WriteLine();
                   }
                }
             }
          }
       }
    }

     

    Compile it and run it, you have your very own Lua console to fool around with. Not very useful as it is, but it's a start. The next thing we'd want to do is to expose some of our own functions to the Lua virtual machine. Again, LuaInterface comes to the rescue: Lua.RegisterFunction(Name, Target, Method) will do just that. The parameters needed are a string, an object instance and a MethodInfo instance for the method we want.

    If you don't know what reflection is, a brief introduction is in order. If you do, just skip to the next paragraph. C# (like Java) has a very nifty feature: reflection. In a nutshell, it lets you rip apart any class, property or method at run time, without needing to know anything about it at build time. The MethodInfo instance we have to pass to the Lua VM is the reflected method taken from the object. We'll make use of it for quite a lot of things later on.

    The first function we could expose to Lua would be a quit function to get rid of that horrible hack in the main loop. Our quit func could be:

     

    public void quit()
    {
       bRunning 
    = false;
    }

     

    Amazingly simple, as you see. It just switches the running flag off. To make it available for Lua, we have to modify the main() function a bit:

     

    static void Main(String[] args)
    {
       Program pPrg 
    = new Program();
       Type pPrgType 
    = pPrg.GetType();
       MethodInfo mInfo 
    = pPrgType.GetMethod("quit");
       pPrg.pLuaVM.RegisterFunction(
    "quit", pPrg, mInfo);
       pPrg.Run();
    }

     

    Now, take out the ugly hack, the Run method looks like this:

     

    public void Run()
    {
       String strInput;

       
    while (bRunning)
       {
          Console.Write(
    "");

          strInput 
    = Console.ReadLine();
          Console.WriteLine();
          
    try
          {
             pLuaVM.DoString(strInput);
          }
          
          
    catch (Exception ex)
          {
             Console.WriteLine(ex.Message);
          }

          
    finally
          {
             Console.WriteLine();
          }
       }
    }

     

    Add System.Reflection to the list of usages and recompile. Run and now whenever you call quit() from the console, it will actually be Lua making it happen. Of course, adding functions like this is a bit awkward if you end up having hundreds of them. It also requires you to touch several parts of the program if you want to add a new function, which often leads to forgetting about some part of the process. Wouldn't it be nice if we could just flag a function somehow in it's declaration and have it automagically picked up by the Lua VM? That way, we would just have to worry about writing them. To fix this, we'll have a look at one of my favourite features of C#: Attributes.

    Attributes in C# are a special class (and descendants) which exist linked with other language elements. They can be attached to class declarations, method declarations, properties, local variables or well, pretty much everything. Then, at run time, you can access them via reflection. The power of this is simply incredible, as we'll see in a moment.

    First, we'll need a custom attribute class. Nothing too complicated:

     

    public class AttrLuaFunc : Attribute
    {
        
    private String FunctionName;
        
    private String FunctionDoc;
        
    private String[] FunctionParameters = null;

        
    public AttrLuaFunc(String strFuncName, String strFuncDoc, params String[] strParamDocs)
        {
            FunctionName 
    = strFuncName;
            FunctionDoc 
    = strFuncDoc;
            FunctionParameters 
    = strParamDocs;
        }

        
    public AttrLuaFunc(String strFuncName, String strFuncDoc)
        {
            FunctionName 
    = strFuncName;
            FunctionDoc 
    = strFuncDoc;
        }

        
    public String getFuncName()
        {
            
    return FunctionName;
        }

        
    public String getFuncDoc()
        {
            
    return FunctionDoc;
        }

        
    public String[] getFuncParams()
        {
            
    return FunctionParameters;
        }
    }

     

    It has a function name, a function "doc" string and an array of parameter definitions. With it, the declaration of our "quit" function would look like this:

     

    [AttrLuaFunc("quit""Exit the program.")]
    public void quit()
    {
        bRunning 
    = false;
    }

     

    Next, we want another class to hold the structure of functions exposed to Lua, just to keep track of everything and have some fancy help built in:

     

    public class LuaFuncDescriptor
    {
        
    private String FunctionName;
        
    private String FunctionDoc;
        
    private ArrayList FunctionParameters;
        
    private ArrayList FunctionParamDocs;
        
    private String FunctionDocString;

        
    public LuaFuncDescriptor(String strFuncName, String strFuncDoc, ArrayList strParams, 
                                 ArrayList strParamDocs)
        {
            FunctionName 
    = strFuncName;
            FunctionDoc 
    = strFuncDoc;
            FunctionParameters 
    = strParams;
            FunctionParamDocs 
    = strParamDocs;

            String strFuncHeader 
    = strFuncName + "(%params%) - " + strFuncDoc;
            String strFuncBody 
    = " ";
            String strFuncParams 
    = "";

            Boolean bFirst 
    = true;
                
            
    for (int i = 0; i < strParams.Count; i++)
            {
                
    if (!bFirst)
                    strFuncParams 
    += "";

                strFuncParams 
    += strParams[i];
                strFuncBody 
    += " " + strParams[i] + " " + strParamDocs[i] + " ";

                bFirst 
    = false;
            }

            strFuncBody 
    = strFuncBody.Substring(0, strFuncBody.Length - 1);
            
    if (bFirst)
                strFuncBody 
    = strFuncBody.Substring(0, strFuncBody.Length - 1);

            FunctionDocString 
    = strFuncHeader.Replace("%params%", strFuncParams) + strFuncBody;
        }

        
    public String getFuncName()
        {
            
    return FunctionName;
        }

        
    public String getFuncDoc()
        {
            
    return FunctionDoc;
        }

        
    public ArrayList getFuncParams()
        {
            
    return FunctionParameters;
        }

        
    public ArrayList getFuncParamDocs()
        {
            
    return FunctionParamDocs;
        }

        
    public String getFuncHeader()
        {
            
    if (FunctionDocString.IndexOf(" "== -1)
                
    return FunctionDocString;

            
    return FunctionDocString.Substring(0, FunctionDocString.IndexOf(" "));
        }

        
    public String getFuncFullDoc()
        {
            
    return FunctionDocString;
        }
    }

     

    We want the function to be called "quit" in Lua, and its helpful doc string just tells the user what it does. We also have a function descriptor to keep track of all added functions. So far so good, now how we do make Lua aware of those attributes to pick everything up? LuaInterface has nothing like that (yet), but we can make it fairly easily with a function. Let's call it "registerLuaFunctions":

     

    public static void registerLuaFunctions(Object pTarget)
    {
        
    // Sanity checks
        if (pLuaVM == null || pLuaFuncs == null)
            
    return;

        
    // Get the target type
        Type pTrgType = pTarget.GetType();

        
    // ... and simply iterate through all it's methods
        foreach (MethodInfo mInfo in pTrgType.GetMethods())
        {
            
    // ... then through all this method's attributes
            foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo))
            {
                
    // and if they happen to be one of our AttrLuaFunc attributes
                if (attr.GetType() == typeof(AttrLuaFunc))
                {
                    AttrLuaFunc pAttr 
    = (AttrLuaFunc) attr;
                    Hashtable pParams 
    = new Hashtable();

                    
    // Get the desired function name and doc string, along with parameter info
                    String strFName = pAttr.getFuncName();
                    String strFDoc 
    = pAttr.getFuncDoc();
                    String[] pPrmDocs 
    = pAttr.getFuncParams();

                    
    // Now get the expected parameters from the MethodInfo object
                    ParameterInfo[] pPrmInfo = mInfo.GetParameters();

                    
    // If they don't match, someone forgot to add some documentation to the 
                    
    // attribute, complain and go to the next method
                    if (pPrmDocs != null && (pPrmInfo.Length != pPrmDocs.Length))
                    {
                        Console.WriteLine(
    "Function " + mInfo.Name + " (exported as " + 
                                          strFName 
    + ") argument number mismatch. Declared " + 
                                          pPrmDocs.Length 
    + " but requires " + 
                                          pPrmInfo.Length 
    + ".");
                        
    break;
                    }

                    
    // Build a parameter <-> parameter doc hashtable
                    for (int i = 0; i < pPrmInfo.Length; i++)
                    {
                        pParams.Add(pPrmInfo[i].Name, pPrmDocs[i]);
                    }

                    
    // Get a new function descriptor from this information
                    LuaFuncDescriptor pDesc = new LuaFuncDescriptor(strFName, strFDoc, pParams);

                    
    // Add it to the global hashtable
                    pLuaFuncs.Add(strFName, pDesc);

                    
    // And tell the VM to register it.
                    pLuaVM.RegisterFunction(strFName, pTarget, mInfo);
                }
            }
        }
    }

     

    Now we modify the Program class and constructor to look like this:

     

    public static Hashtable pLuaFuncs = null;

    public Program()
    {
        pLuaVM 
    = new Lua();
        pLuaFuncs 
    = new Hashtable();
        registerLuaFunctions(
    this);
    }

     

    That's it. Now, as soon as you instantiate the Program class, it will register all it's functions automatically. Since the LuaVM, function hashtable and registerLuaFuncs method are all static, you can call them from wherever and add new functions to it, keeping a single centralized VM and function list.

    We've being adding a lot of "Doc" stuff we have no use for yet. It's time to fix that. The following two functions make all it happen for us:

     

    [AttrLuaFunc("help""List available commands.")]
    public void help()
    {
        Console.WriteLine(
    "Available commands: ");
        Console.WriteLine();

        IDictionaryEnumerator Funcs 
    = pLuaFuncs.GetEnumerator();
        
    while (Funcs.MoveNext())
        {
            Console.WriteLine(((LuaFuncDescriptor)Funcs.Value).getFuncHeader());
        }
    }

    [AttrLuaFunc(
    "helpcmd""Show help for a given command""Command to get help of.")]
    public void help(String strCmd)
    {
        
    if (!pLuaFuncs.ContainsKey(strCmd))
        {
            Console.WriteLine(
    "No such function or package: " + strCmd);
            
    return;
        }

        LuaFuncDescriptor pDesc 
    = (LuaFuncDescriptor)pLuaFuncs[strCmd];
        Console.WriteLine(pDesc.getFuncFullDoc());
    }

     

    It's as simple as that, just write those two functions and they get inserted without you having to move a finger. They are straightforward. The first one lists all available commands (exposed from your application) and the second one gives detailed help on any command. Compile, build and try:

    help()
    helpcmd("help")
    helpcmd("helpcmd")
    

    Impressive, huh?

    There is one significant improvement that can be made here and it's having functions grouped in packages for each object registering it's functions. Think of it as an exercise left to the reader. In any case, it's included in the full project here.

    Discuss this article in the forums


    Date this article was posted to GameDev.net: 11/7/2005
    (Note that this date does not necessarily correspond to the date the article was written)

    发表于 @ 2008年04月13日 10:23:00|评论(loading...)|编辑

    新一篇: SCSL,J2ME源代码 | 旧一篇: lua 5.0的实现(翻译)1,2,3,4,5部分

    评论:没有评论。

    发表评论  


    登录
    Csdn Blog version 3.1a
    Copyright © 张宇