摘要: 《Pro Android C++ with the NDK》第4章 Copyright © 2012 by Onur CinarChapter 4: Auto-Generate JNI Code Using SWIG In the previous chapter you explored JNI technology and you learned how to connect native code to a Java application. As noted, implementing JNI wrapper code and handling the translation阅读全文
posted @ 2013-05-21 09:37 张云贵 阅读(14) 评论(0) 编辑

http://www.swig.org/Doc2.0/Android.html (原文好像被墙,特转)

 

18 SWIG and Android

This chapter describes SWIG's support of Android.

18.1 Overview

The Android chapter is fairly short as support for Android is the same as for Java, where the Java Native Interface (JNI) is used to call from Android Java into C or C++ compiled code. Everything in the Java chapter applies to generating code for access from Android Java code. This chapter contains a few Android specific notes and examples.

18.2 Android examples

18.2.1 Examples introduction

The examples require the Android SDK and Android NDK which can be installed as per instructions in the links. The Eclipse version is not required for these examples as just the command line tools are used (shown for Linux as the host, but Windows will be very similar, if not identical in most places). Add the SDK tools and NDK tools to your path and create a directory somewhere for your Android projects (adjust PATH as necessary to where you installed the tools):

 $ export
 $ mkdir AndroidApps 
 $ cd AnrdoidApps

The examples use a target id of 1. This might need changing depending on your setup. After installation of the Android SDK, the available target ids can be viewed by running the command below. Please adjust the id to suit your target device.

 $ android list targets

The following examples are shipped with SWIG under the Examples/android directory and include a Makefile to build and install each example.

18.2.2 Simple C example

This simple C example shows how to call a C function as well as read and modify a global variable. First we'll create and build a pure Java Android app. Afterwards the JNI code will be generated by SWIG and built into the app. First create and build an app called SwigSimple in a subdirectory called simple using the commands below. Adjust the --target id as mentioned earlier in the Examples introduction . Managing Projects from the Command Line on the Android developer's site is a useful reference for these steps.

 $ android create project --target 1 --name SwigSimple --path ./simple --activity SwigSimple --package org.swig.simple
 $ cd simple
 $ ant debug

Modify src/org/swig/simple/SwigSimple.java from the default to:

 package org.swig.simple;

 import android.app.Activity;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.Button;
 import android.widget.TextView;
 import android.widget.ScrollView;
 import android.text.method.ScrollingMovementMethod;

 public class SwigSimple extends Activity
 {
     TextView outputText = null;
     ScrollView scroller = null;

     /** Called when the activity is first created.  */
     @Override
     public void onCreate(Bundle savedInstanceState)
     {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);

         outputText = (TextView)findViewById(R.id.OutputText);
         outputText.setText("Press 'Run' to start...\n");
         outputText.setMovementMethod(new ScrollingMovementMethod());

         scroller = (ScrollView)findViewById(R.id.Scroller);
     }

     public void onRunButtonClick(View view)
     {
       outputText.append("Started...\n");
       nativeCall();
       outputText.append("Finished!\n");
      
       // Ensure scroll to end of text
       scroller.post(new Runnable() {
         public void run() {
           scroller.fullScroll(ScrollView.FOCUS_DOWN);
         }
       });
     }

     /** Calls into C/C++ code */
     public void nativeCall()
     {
         // TODO
     }
 }

The above simply adds a Run button and scrollable text view as the GUI aspects of the program. The associated resources need to be created, modify res/layout/main.xml as follows:

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     >
 <Button
     android:id="@+id/RunButton"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Run..."  
     android:onClick="onRunButtonClick"
     />
 <ScrollView
     android:id="@+id/Scroller"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     >
 <TextView
     android:id="@+id/OutputText"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     />
 </ScrollView>
 </LinearLayout>

Rebuild the project with your changes:

 $ ant debug

Although there are no native function calls in the code, yet, you may want to check that this simple pure Java app runs before adding in the native calls. First, set up your Android device for hardware debugging, see Using hardware devices on the Android developer's site. When complete your device should be listed in those attached, something like:

 $ adb devices
 List of devices attached 
 A32-6DBE0001-9FF80000-015D62C3-02018028 device

This means you are now ready to install the application...

 $ adb install bin/SwigSimple-debug.apk 
 95 KB/s (4834 bytes in 0.049s)
	 pkg: /data/local/tmp/SwigSimple-debug.apk
 Success

The newly installed 'SwigSimple' app will be amongst all your other applications on the home screen. Run the app and it will show a Run button text box below it. Press the Run button to see the simple text output.

The application can be uninstalled like any other application and in fact must be uninstalled before installing an updated version. Uninstalling is quite easy too from your host computer:

 $ adb uninstall org.swig.simple
 Success

Now that you have a pure Java Android app working, let's add some JNI code generated from SWIG.

First create a jni subdirectory and then create some C source code in jni/example.c :

 /* File : example.c */

 /* A global variable */
 double Foo = 3.0;

 /* Compute the greatest common divisor of positive integers */
 int gcd(int x, int y) {
   int g;
   g = y;
   while (x > 0) {
     g = x;
     x = y % x;
     y = g;
   }
   return g;
 }

Create a SWIG interface file for this C code, jni/example.i :

 /* File : example.i */
 %module example

 %inline %{
 extern int gcd(int x, int y);
 extern double Foo;
 %}

Invoke SWIG as follows:

 $ swig -java -package org.swig.simple -outdir src/org/swig/simple -o jni/example_wrap.c jni/example.i

SWIG generates the following files:

  • src/org/swig/simple/exampleJNI.java
  • src/org/swig/simple/example.java
  • jni/example_wrap.c

Next we need to create a standard Android NDK build system file jni/Android.mk :

 # File: Android.mk
 LOCAL_PATH := $(call my-dir)

 include $(CLEAR_VARS)

 LOCAL_MODULE := example
 LOCAL_SRC_FILES := example_wrap.c example.c

 include $(BUILD_SHARED_LIBRARY)

See the Android NDK documentation for more on the NDK build system and getting started with the NDK. A simple invocation of ndk-build will compile the .c files and generate a shared object/system library. Output will be similar to:

 $ ndk-build
 Compile thumb : example <= example_wrap.c
 Compile thumb : example <= example.c
 SharedLibrary : libexample.so
 Install : libexample.so => libs/armeabi/libexample.so

Now that the C JNI layer has been built, we can write Java code to call into the this layer. Modify the nativeCall method in src/org/swig/simple/SwigSimple.java to call the JNI code as follows and add the static constructor to load the system library containing the compiled JNI C code:

     /** Calls into C/C++ code */
     public void nativeCall()
     {
       // Call our gcd() function
      
       int x = 42;
       int y = 105;
       int g = example.gcd(x,y);
       outputText.append("The greatest common divisor of " + x + " and " + y + " is " + g + "\n");

       // Manipulate the Foo global variable

       // Output its current value
       double foo = example.getFoo();
       outputText.append("Foo = " + foo + "\n");

       // Change its value
       example.setFoo(3.1415926);

       // See if the change took effect
       outputText.append("Foo = " + example.getFoo() + "\n");

       // Restore value
       example.setFoo(foo);
     }

     /** static constructor */
     static {
         System.loadLibrary("example");
     }

Compile the Java code as usual, uninstall the old version of the app if still installed and re-install the new app:

 $ ant debug
 $ adb uninstall org.swig.simple
 $ adb install bin/SwigSimple-debug.apk 

Run the app again and this time you will see the output pictured below, showing the result of calls into the C code:

Android screenshot of SwigSimple example

18.2.3 C++ class example

The steps for calling C++ code are almost identical to those in the previous C code example. All the steps required to compile and use a simple hierarchy of classes for shapes are shown in this example.

First create an Android project called SwigClass in a subdirectory called class . The steps below create and build a the JNI C++ app. Adjust the --target id as mentioned earlier in the Examples introduction .

 $ android create project --target 1 --name SwigClass --path ./class --activity SwigClass --package org.swig.classexample
 $ cd class

Now create a jni subdirectory and then create a C++ header file jni/example.h which defines our hierarchy of shape classes:

 /* File : example.h */

 class Shape {
 public:
   Shape() {
     nshapes++;
   }
   virtual ~Shape() {
     nshapes--;
   };
   double x, y;   
   void move(double dx, double dy);
   virtual double area(void) = 0;
   virtual double perimeter(void) = 0;
   static int nshapes;
 };

 class Circle : public Shape {
 private:
   double radius;
 public:
   Circle(double r) : radius(r) { };
   virtual double area(void);
   virtual double perimeter(void);
 };

 class Square : public Shape {
 private:
   double width;
 public:
   Square(double w) : width(w) { };
   virtual double area(void);
   virtual double perimeter(void);
 };

and create the implementation in the jni/example.cpp file:

 /* File : example.cpp */

 #include "example.h"
 #define M_PI 3.14159265358979323846

 /* Move the shape to a new location */
 void Shape::move(double dx, double dy) {
   x += dx;
   y += dy;
 }

 int Shape::nshapes = 0;

 double Circle::area(void) {
   return M_PI*radius*radius;
 }

 double Circle::perimeter(void) {
   return 2*M_PI*radius;
 }

 double Square::area(void) {
   return width*width;
 }

 double Square::perimeter(void) {
   return 4*width;
 }

Create a SWIG interface file for this C++ code in jni/example.i :

 /* File : example.i */
 %module example

 %{
 #include "example.h"
 %}

 /* Let's just grab the original header file here */
 %include "example.h"

Invoke SWIG as follows, note that the -c++ option is required for C++ code:

 $ swig -c++ -java -package org.swig.classexample -outdir src/org/swig/classexample -o jni/example_wrap.cpp jni/example.i

SWIG generates the following files:

  • src/org/swig/classexample/Square.java
  • src/org/swig/classexample/exampleJNI.java
  • src/org/swig/classexample/example.java
  • src/org/swig/classexample/Circle.java
  • src/org/swig/classexample/Shape.java
  • jni/example_wrap.cpp

Next we need to create an Android NDK build system file for compiling the C++ code jni/Android.mk . The -frtti compiler flag isn't strictly needed for this example, but is needed for any code that uses C++ RTTI:

 # File: Android.mk
 LOCAL_PATH := $(call my-dir)

 include $(CLEAR_VARS)

 LOCAL_MODULE := example
 LOCAL_SRC_FILES := example_wrap.cpp example.cpp
 LOCAL_CFLAGS := -frtti

 include $(BUILD_SHARED_LIBRARY)

A simple invocation of ndk-build will compile the .cpp files and generate a shared object/system library. Output will be similar to:

 $ ndk-build
 Compile++ thumb : example <= example_wrap.cpp
 Compile++ thumb : example <= example.cpp
 StaticLibrary : libstdc++.a
 SharedLibrary : libexample.so
 Install : libexample.so => libs/armeabi/libexample.so

Now that the C JNI layer has been built, we can write Java code to call into this layer. Modify src/org/swig/classexample/SwigClass.java from the default to:

 package org.swig.classexample;

 import android.app.Activity;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.Button;
 import android.widget.TextView;
 import android.widget.ScrollView;
 import android.text.method.ScrollingMovementMethod;

 public class SwigClass extends Activity
 {
     TextView outputText = null;
     ScrollView scroller = null;

     /** Called when the activity is first created.  */
     @Override
     public void onCreate(Bundle savedInstanceState)
     {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);

         outputText = (TextView)findViewById(R.id.OutputText);
         outputText.setText("Press 'Run' to start...\n");
         outputText.setMovementMethod(new ScrollingMovementMethod());

         scroller = (ScrollView)findViewById(R.id.Scroller);
     }

     public void onRunButtonClick(View view)
     {
       outputText.append("Started...\n");
       nativeCall();
       outputText.append("Finished!\n");
      
       // Ensure scroll to end of text
       scroller.post(new Runnable() {
         public void run() {
           scroller.fullScroll(ScrollView.FOCUS_DOWN);
         }
       });
     }

     /** Calls into C/C++ code */
     public void nativeCall()
     {
       // ----- Object creation -----

       outputText.append( "Creating some objects:\n" );
       Circle c = new Circle(10);
       outputText.append( " Created circle " + c + "\n");
       Square s = new Square(10);
       outputText.append( " Created square " + s + "\n");

       // ----- Access a static member -----

       outputText.append( "\nA total of " + Shape.getNshapes() + " shapes were created\n" );

       // ----- Member data access -----

       // Notice how we can do this using functions specific to
       // the 'Circle' class.
       c.setX(20);
       c.setY(30);

       // Now use the same functions in the base class
       Shape shape = s;
       shape.setX(-10);
       shape.setY(5);

       outputText.append( "\nHere is their current position:\n" );
       outputText.append( " Circle = (" + c.getX() + " " + c.getY() + ")\n" );
       outputText.append( " Square = (" + s.getX() + " " + s.getY() + ")\n" );

       // ----- Call some methods -----

       outputText.append( "\nHere are some properties of the shapes:\n" );
       Shape[] shapes = {c,s};
       for (int i=0; i<shapes.length; i++)
       {
         outputText.append( " " + shapes[i].toString() + "\n" );
         outputText.append( " area = " + shapes[i].area() + "\n" );
         outputText.append( " perimeter = " + shapes[i].perimeter() + "\n" );
       }

       // Notice how the area() and perimeter() functions really
       // invoke the appropriate virtual method on each object.

       // ----- Delete everything -----

       outputText.append( "\nGuess I'll clean up now\n" );

       // Note: this invokes the virtual destructor
       // You could leave this to the garbage collector
       c.delete();
       s.delete();

       outputText.append( Shape.getNshapes() + " shapes remain\n" );
       outputText.append( "Goodbye\n" );
     }

     /** static constructor */
     static {
         System.loadLibrary("example");
     }
 }

Note the static constructor and the interesting JNI code is in the nativeCall method. The remaining code deals with the GUI aspects which are identical to the previous C simple example. Modify res/layout/main.xml to contain the xml for the 'Run' button and scrollable text view:

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     >
 <Button
     android:id="@+id/RunButton"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Run..."  
     android:onClick="onRunButtonClick"
     />
 <ScrollView
     android:id="@+id/Scroller"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     >
 <TextView
     android:id="@+id/OutputText"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     />
 </ScrollView>
 </LinearLayout>

Compile the Java code as usual, uninstall the old version of the app if installed and re-install the new app:

 $ ant debug
 $ adb uninstall org.swig.classexample
 $ adb install bin/SwigClass-debug.apk 

Run the app to see the result of calling the C++ code from Java:

Android screenshot of SwigClass example

18.2.4 Other examples

The Examples/android directory contains further examples which can be run and installed in a similar manner to the previous two examples.

Note that the 'extend' example is demonstrates the directors feature. Normally C++ exception handling and the STL is not available by default in the version of g++ shipped with Android, but this example turns these features on as described in the next section.

18.3 C++ STL

Should the C++ Standard Template Library (STL) be required, an Application.mk file needs to be created in the same directory as the Android.mk directory containing information about the STL to use. See the NDK documentation in the $NDKROOT/docs folder especially CPLUSPLUS-SUPPORT.html. Below is an example of the Application.mk file to make the STLport static library available for use:

 # File: Application.mk
 APP_STL := gnustl_static
posted @ 2013-04-04 23:27 张云贵 阅读(58) 评论(0) 编辑

基于Android平台多个Icon的APk——实现多程序入口总结
某些情况下,我们需要为我们的apk设置多个执行入口,也就是安装后在应用程序列表中出现多个ICON图标,各个ICON是APP不同模块的入口点。有一个现实的例子:系统中的联系人和电话这两个程序(如下图所示)

现在越来越多的应用也具备这样的设置,比如百度应用(百度应用+应用管理),腾讯应用宝等。
下面我们来总结一下网上流传广泛的3种实现方式。   
                           
实现方式1:intent-filter                              
给相应的Activity增加intent-filter
?
<ativity android:name="A2" android:label="@string/app_name2">
   <intent-filter>
      <action android:name="android.intent.action.MAIN" />  
      <category android:name="android.intent.category.LAUNCHER" />  
   </intent-filter>  
</activity>  
  
实现方式2:process属性
                              
Activity有一个重要的属性process,这个属性是指定Activity运行时所在的进程。没有指定此属性的话,所有程序组件运行在应用程序默 认的进程中,这个进程名跟应用程序的包名一致。中所有组建元素的process属性能够为该组件设定一个新的默认值。但是任何组件都可以覆盖这个默认值, 允许你将你的程序放在多进程中运行。如果这个属性被分配的名字以:开头,当这个activity运行时,一个新的专属于这个程序的进程将会被创建。
实现如下:
?
<activity android:name=".A1"
    android:label="@string/app_name"
    android:process=":process.main">
   <intent-filter>
     <action android:name="android.intent.action.MAIN" />
     <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
</activity>
     
<activity android:name=".A2"
    android:label="@string/app_name2"
    android:process=":process.sub"
    android:icon="@drawable/icon2"
    android:launchMode ="singleInstance">
   <intent-filter>
     <action android:name="android.intent.action.MAIN" />
     <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
</activity>
  
实现方式3:activity-alias
alias => 别名
                              
实现如下:
?
<activity-alias
   android:name="A3"
   android:icon="@drawable/icon2"
   android:label="@string/app_name2"
   android:targetActivity=".A2" >
   <intent-filter>
      <action android:name="android.intent.action.MAIN" />
      <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
</activity-alias>
  这里targetActivity作用是让A3与A2公用一个界面,也就是给A2起了个“小名”叫A3,A2在Manifest.xml中只是一个正 常注册的Activity,但是A3却在桌面上有一个程序图标,单击图标可以进入A2了。完整的Manifest.xml如下:
?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.wang.multiicon"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".A1"
            android:icon="@drawable/ic_launcher_contacts"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".A2"
            android:label="@string/app_name2" >
        </activity>
        <activity-alias
            android:name="A3"
            android:icon="@drawable/ic_launcher_phone"
            android:label="@string/app_name2"
            android:targetActivity=".A2" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity-alias>
    </application>

</manifest>
  需要说明的一点:系统Contacts应用就是使用第三种方式实现的多程序入口的。

总结:上面三种实现方式其实原理都是一样的,都是为第二个Activity添加
"<action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />"
intent-filter为程序增加入口图标。

http://www.eoeandroid.com/forum.php?mod=viewthread&tid=193499&extra=page%3D1&page=1

posted @ 2013-02-27 13:37 张云贵 阅读(59) 评论(0) 编辑

http://sourceforge.net/projects/touchvg/files/ShapeEditor.exe.rar/download

用了不到4天基于TouchVG框架写的一个Windows矢量绘图软件,功能超多,体积超小,已经投入使用,感兴趣的请下载试试。

posted @ 2013-02-03 09:27 张云贵 阅读(127) 评论(0) 编辑

外部接口类隐藏JSON细节:

#ifndef __GEOMETRY_JSONSTORAGE_H_
#define __GEOMETRY_JSONSTORAGE_H_

struct MgStorage;

//! JSON序列化适配器类
/*! \ingroup GEOM_SHAPE
*/
class MgJsonStorage
{
public:
    MgJsonStorage();
    ~MgJsonStorage();

    //! 给定JSON内容,返回存取接口对象以便开始读取
    MgStorage* storageForRead(const char* content);

    //! 返回存取接口对象以便开始写数据,写完可调用 getContentWriten()
    MgStorage* storageForWrite();

    //! 返回写完后的JSON内容
    const char* getContentWriten() const;

private:
    class Impl;
    Impl* _impl;
};

#endif // __GEOMETRY_JSONSTORAGE_H_

 

内部实现文件使用rapidjson框架,代码少、运行速度比iOS和Android的Json框架快。

#include "mgjsonstorage.h"
#include <mgstorage.h>
#include <vector>
#include "rapidjson/document.h"     // rapidjson's DOM-style API
#include "rapidjson/prettywriter.h" // for stringify JSON
#include "rapidjson/filestream.h"   // wrapper of C stream for prettywriter as output
#include "rapidjson/stringbuffer.h"

using namespace rapidjson;

//! JSON序列化适配器类,内部实现类
class MgJsonStorage::Impl : public MgStorage
{
public:
    Impl() {}

    void clear();
    const char* getContent() const;
    void setContent(const char* content);

private:
    bool readNode(const char* name, int index, bool ended);
    bool writeNode(const char* name, int index, bool ended);

    int readInt(const char* name, int defvalue);
    bool readBool(const char* name, bool defvalue);
    float readFloat(const char* name, float defvalue);
    int readFloatArray(const char* name, float* values, int count);
    int readString(const char* name, char* value, int count);

    void writeInt(const char* name, int value);
    void writeBool(const char* name, bool value);
    void writeFloat(const char* name, float value);
    void writeFloatArray(const char* name, const float* values, int count);
    void writeString(const char* name, const char* value);

private:
    Document _doc;
    std::vector<Value*> _stack;
    StringBuffer _strbuf;
};

MgJsonStorage::MgJsonStorage()
{
    _impl = new Impl();
}

MgJsonStorage::~MgJsonStorage()
{
    delete _impl;
}

const char* MgJsonStorage::getContentWriten() const
{
    return _impl->getContent();
}

MgStorage* MgJsonStorage::storageForRead(const char* content)
{
    _impl->clear();
    _impl->setContent(content);

    return _impl;
}

MgStorage* MgJsonStorage::storageForWrite()
{
    _impl->clear();

    return _impl;
}

void MgJsonStorage::Impl::clear()
{
    _doc.SetNull();
    _stack.clear();
    _strbuf.Clear();
}

const char* MgJsonStorage::Impl::getContent() const
{
    return _strbuf.GetString();
}

void MgJsonStorage::Impl::setContent(const char* content)
{
    if (content && *content) {
        _doc.Parse<0>(content);         // DOM解析
        if (_doc.HasParseError()) {
            const char* err = _doc.GetParseError();
            err = err;
        }
    }
}

bool MgJsonStorage::Impl::readNode(const char* name, int index, bool ended)
{
    if (!ended) {                       // 开始一个新节点
        char tmpname[32];
        if (index >= 0) {               // 形成实际节点名称
            sprintf(tmpname, "%s%d", name, index + 1);
            name = tmpname;
        }

        Value &parent = _stack.empty() ? _doc : *_stack.back();

        if (!parent.IsObject() || !parent.HasMember(name)) {    // 没有节点则返回
            return false;
        }

        _stack.push_back(&parent[name]);    // 当前JSON对象压栈
    }
    else {                              // 当前节点读取完成
        if (!_stack.empty()) {
            _stack.pop_back();          // 出栈
        }
        if (_stack.empty()) {           // 根节点已出栈
            clear();
        }
    }

    return true;
}

int MgJsonStorage::Impl::readInt(const char* name, int defvalue)
{
    int ret = defvalue;
    Value *node = _stack.empty() ? NULL : _stack.back();

    if (node && node->HasMember(name)) {
        const Value &item = (*node)[name];

        if (item.IsInt()) {
            ret = item.GetInt();
        }
        else if (item.IsUint()) {
            ret = item.GetUint();
        }
        else {
            ret = ret;
        }
    }

    return ret;
}

bool MgJsonStorage::Impl::readBool(const char* name, bool defvalue)
{
    bool ret = defvalue;
    Value *node = _stack.empty() ? NULL : _stack.back();

    if (node && node->HasMember(name)) {
        const Value &item = node->GetMember(name);

        if (item.IsBool()) {
            ret = item.GetBool();
        }
        else {
            ret = ret;
        }
    }

    return ret;
}

float MgJsonStorage::Impl::readFloat(const char* name, float defvalue)
{
    float ret = defvalue;
    Value *node = _stack.empty() ? NULL : _stack.back();

    if (node && node->HasMember(name)) {
        const Value &item = node->GetMember(name);

        if (item.IsDouble()) {
            ret = (float)item.GetDouble();
        }
        else if (item.IsInt()) {    // 浮点数串可能没有小数点,需要判断整数
            ret = (float)item.GetInt();
        }
        else {
            ret = ret;
        }
    }

    return ret;
}

int MgJsonStorage::Impl::readFloatArray(const char* name, float* values, int count)
{
    int ret = 0;
    Value *node = _stack.empty() ? NULL : _stack.back();

    if (node && node->HasMember(name)) {
        const Value &item = node->GetMember(name);

        if (item.IsArray()) {
            ret = item.Size();
            if (values) {
                count = ret < count ? ret : count;
                ret = 0;
                for (int i = 0; i < count; i++) {
                    const Value &v = item[i];

                    if (v.IsDouble()) {
                        values[ret++] = (float)v.GetDouble();
                    }
                    else if (v.IsInt()) {
                        values[ret++] = (float)v.GetInt();
                    }
                    else {
                        ret = ret;
                    }
                }
            }
        }
        else {
            ret = ret;
        }
    }

    return ret;
}

int MgJsonStorage::Impl::readString(const char* name, char* value, int count)
{
    int ret = 0;
    Value *node = _stack.empty() ? NULL : _stack.back();

    if (node && node->HasMember(name)) {
        const Value &item = node->GetMember(name);

        if (item.IsString()) {
            ret = item.GetStringLength();
            if (value) {
                ret = ret < count ? ret : count;
                strncpy(value, item.GetString(), ret);
            }
        }
        else {
            ret = ret;
        }
    }

    return ret;
}

bool MgJsonStorage::Impl::writeNode(const char* name, int index, bool ended)
{
    if (!ended) {                       // 开始一个新节点
        char tmpname[32];
        if (index >= 0) {               // 形成实际节点名称
            sprintf(tmpname, "%s%d", name, index + 1);
            name = tmpname;
        }

        if (_stack.empty()) {
            _doc.SetObject();
        }

        Value &parent = _stack.empty() ? _doc : *_stack.back();
        Value tmpnode(kObjectType);
        Value namenode(name, _doc.GetAllocator());  // 节点名是临时串,要复制
        
        parent.AddMember(namenode, tmpnode, _doc.GetAllocator());
        _stack.push_back(&(parent.MemberEnd() - 1)->value); // 新节点压栈
    }
    else {                              // 当前节点写完
        if (!_stack.empty()) {
            _stack.pop_back();          // 出栈
        }
        if (_stack.empty()) {           // 根节点已出栈
            Document::AllocatorType allocator;
            Writer<StringBuffer> writer(_strbuf, &allocator);
            _doc.Accept(writer);        // DOM树转换到文本流

            _doc.SetNull();
            _stack.clear();
        }
    }

    return true;
}

void MgJsonStorage::Impl::writeInt(const char* name, int value)
{
    _stack.back()->AddMember(name, value, _doc.GetAllocator());
}

void MgJsonStorage::Impl::writeBool(const char* name, bool value)
{
    _stack.back()->AddMember(name, value, _doc.GetAllocator());
}

void MgJsonStorage::Impl::writeFloat(const char* name, float value)
{
    _stack.back()->AddMember(name, (double)value, _doc.GetAllocator());
}

void MgJsonStorage::Impl::writeFloatArray(const char* name, const float* values, int count)
{
    Value node(kArrayType);

    for (int i = 0; i < count; i++) {
        node.PushBack((double)values[i], _doc.GetAllocator());
    }
    _stack.back()->AddMember(name, node, _doc.GetAllocator());
}

void MgJsonStorage::Impl::writeString(const char* name, const char* value)
{
    _stack.back()->AddMember(name, value, _doc.GetAllocator());
}

 

 

posted @ 2013-01-07 23:16 张云贵 阅读(202) 评论(0) 编辑
摘要: http://c.hiphotos.baidu.com/album/s%3D1600%3Bq%3D90/sign=eb04ea27828ba61edbeecc297104ac7b/09fa513d269759ee675c8c26b2fb43166c22dfcb.jpghttp://xiangce.baidu.com/picture/detail/8a4ead18600fedff25a2f1f3cbabc3493aa916e6阅读全文
posted @ 2012-12-17 09:29 张云贵 阅读(77) 评论(0) 编辑
摘要: [用例的粒度问题]首先没有粒度问题,通常是把步骤当为用例引起的,外部执行者一次有意义的完整交互就是一个用例,执行者可以暂时放心离开了。步骤复杂可扩展为子用例。以买火车为例,抢到票了不支付就不能放心离开,支付票款就不是一个主用例,后补支付可为候选路径。[系统用例]直接交互的某领导做了几件事,可能是不同角色、几件独立事。一次有意义的完整交互并得到想要结果,可放心离开,就是一个用例。其后其他人处理是其他系统用例。[用例到功能]用例模型到功能模型是在系统分析中进行的,后者根据已有软件资源,分配职责到不同逻辑模块,得到模块列表和职责(功能)列表,即用例实现。系分主要采用三大视图,领域分析结构视图、行为动阅读全文
posted @ 2012-12-04 08:30 张云贵 阅读(67) 评论(0) 编辑
摘要: 应公司要求,准备按下面的培训大纲讲,不知道是否合适。UML建模基础培训大纲(下周一 14:00-17:00)------------------------------------------培训目标:了解常见UML图的用法和使用场合,能正确绘制易于理解的模型图。培训大纲:一、UML建模总览介绍在不同开发阶段可能用到的主要UML图,分析其建模作用和不同图的区别,提及建模核心思想。二、案例分析和建模以公司产品为案例,介绍常见的UML图的基本用法,解析建模方法和要点。结合 EA 工具演示建模步骤和快速建模方法。主要内容点:1、层图:常见版型、包间关系、常见架构的画法2、类图:七种关系辨析、细化准则阅读全文
posted @ 2012-11-27 17:56 张云贵 阅读(91) 评论(1) 编辑
摘要: EA介绍与UML建模入门-200910面向对象需求分析实例-200910UML设计建模实用入门-201004UML设计建模实用介绍-201004UML设计建模-201104UML实效建模-201005下周将新版《UML实效建模》,下下周分两个或三个专题《UML动态建模》、《UML用例建模》、《UML敏捷建模》。阅读全文
posted @ 2012-11-26 11:17 张云贵 阅读(100) 评论(0) 编辑
摘要: 为了准备培训素材,重新阅读了《UML风格》电子版,感觉很有收获。第2章 一般画图准则2.1 可读性准则2.2 简单性准则2.3 命名准则2.4 一般准则第3章 通用UML建模元素的准则3.1 应用于UML注释的准则3.2 应用于UML衍型的准则3.3 应用于UML框的准则3.4 应用于UML接口的准则第4章 UML用例图4.1 用例准则4.2 参与者准则4.3 关系准则4.4 系统边界框准则第5章 UML类图5.1 一般准则5.2 类的风格准则5.3 关系准则5.4 关联准则5.5 继承准则5.6 聚合和组合的准则第6章 UML包图6.1 类的包图准则6.2 用例的包图准则6.3 包准则第7章阅读全文
posted @ 2012-11-26 11:10 张云贵 阅读(64) 评论(0) 编辑