public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setText("Hello, Android"); setContentView(tv); } }
8) 실행 - Run > Run As > Android Application
* 여기서 상당한 인내심을 발휘해야 한다. 2~3분 정도 기다리면 꽤 그럴듯한 실제 단말 바탕화면이 뜨고 곧 해당 어플을 실행시켜준다.
1. 해당함수가 리턴하는 값이 없는 경우(void 형 함수)에는 Sub 를 사용한다. 2. 함수의 인자가 값을 넘겨주는 경우는 ByVal 을 주소값(포인터)를 넘겨주는 경우는 ByRef를 사용한다. 3. 선언의 제일 마지막에는 해당함수의 리턴형태를 As 를 사용해서 지정해준다. void* 함수처럼 포인터를 리턴하는 경우는 해당 바이트의 수에 맞는 데이터형을 지정한다. ( DLL 에서 32비트 데이터로 리턴을 하면 VB에서도 32비트 데이터형으로 받는다. )
선언이 끝나면 코드에서 사용이 가능한데 사용방법은 C/C++ 에서 함수의 사용과 비슷합니다.
단, Sub 로 선언한 함수의 경우는 Call 명령으로 호출해주도록 합니다. (ex. Call Test_Output() ) . .
hwnd [in] Handle to the window to animate. The calling thread must own this window. dwTime [in] Specifies how long it takes to play the animation, in milliseconds. Typically, an animation takes 200 milliseconds to play. dwFlags [in] Specifies the type of animation. This parameter can be one or more of the following values. Note that, by default, these flags take effect when showing a window. To take effect when hiding a window, use AW_HIDE and a logical OR operator with the appropriate flags.
AW_SLIDE Uses slide animation. By default, roll animation is used. This flag is ignored when used with AW_CENTER. AW_ACTIVATE Activates the window. Do not use this value with AW_HIDE. AW_BLEND Uses a fade effect. This flag can be used only if hwnd is a top-level window. AW_HIDE Hides the window. By default, the window is shown. AW_CENTER Makes the window appear to collapse inward if AW_HIDE is used or expand outward if the AW_HIDE is not used. The various direction flags have no effect. AW_HOR_POSITIVE Animates the window from left to right. This flag can be used with roll or slide animation. It is ignored when used with AW_CENTER or AW_BLEND. AW_HOR_NEGATIVE Animates the window from right to left. This flag can be used with roll or slide animation. It is ignored when used with AW_CENTER or AW_BLEND. AW_VER_POSITIVE Animates the window from top to bottom. This flag can be used with roll or slide animation. It is ignored when used with AW_CENTER or AW_BLEND. AW_VER_NEGATIVE Animates the window from bottom to top. This flag can be used with roll or slide animation. It is ignored when used with AW_CENTER or AW_BLEND.
첫 번째 인자인 hwnd 는 효과를 적용하기위한 윈도우의 핸들이다.
두 번째 인자인 dwTime 은 지정된 효과를 수행할 시간으로 밀리세컨드 단위로 입력한다. 입력값이 작을 수록 에니메이션 효과의 시간이 짧아 지므로 에니메이션이 빠르게 동작한다.
세 번째 인자는 효과의 종류이다.
AW_SLIDE : 기본 인자로 에니메이션 효과를 의미하며 생략해도 슬리이딩 효과가 있는 것 같다. AW_CENTER 가 함께 적용되면 무시된다.
JavaScript에서 Plug-in 내부의 함수를 호출하는 방법을 익혀 봅니다. 서로 다른 형태의 바이너리가 소통할 수 있는 이유는 XPCOM이라는 인터페이스 규약을 따르고 있기 때문입니다.
IDL 파일 생성
그림 1 Add 함수
지금 만들어 보려고 하는 형태는 위 그림에서 설명하는 것처럼 1 + 2를 호출하면 3을 반환하는 함수를 만들어 보려고 하고 있습니다. Function Call처럼 보이는 Add 함수는 Plug-in이 구현하고 있는 함수로서 JavaScript가 호출해서 반환 값을 얻어가고 있는 형태인데요. 바이너리 레벨에서 서로 통신하는 구조는 내부적으로 XPCOM 인터페이스 규칙을 따르고 있기 때문에 가능합니다.
간단해 보이는 Add 함수를 구현함으로써 크게 XPCOM 함수를 구현하는 방법, XPCOM 인터페이스를 구현하는 방법, 인자가 넘어오는 형태, 반환 값을 넘기는 형태 등을 배울 수 있습니다.
가장 첫 번째 단계로 IDL 파일을 만들어 봅시다. IDL 파일은 Interface Description Language로 인터페이스를 정의하는 파일이 되겠습니다. 인터페이스가 필요한 이유는 Add 함수가 어떤 형태로 구현이 되어 있던 간에 외부에서는 인터페이스만 보고 통신할 수 있도록 하기 위함입니다.
그림 2 nsIScriptableObject.idl
위 그림에 작성된 IDL 파일을 보면 #include 부분과 uuid 부분을 제외하면 Class 정의하는 것과 거의 차이가 없어 보입니다. Add 함수는 long 형 2개를 인자로 받고 long형을 반환하는 함수의 형태입니다. 위 내용을 그대로 작성해서 nsIScriptableObject.idl 파일로 저장합니다.
Type Header와 Type Library 파일 생성
앞서 배웠던 xpidl을 이용해서 Type Header와 Type Library를 생성합니다.
결과 파일로 nsIScriptableObject.h 와 nsIScriptableObject.xpt 파일이 생성됩니다.
Scriptable Object 구현 (XPCOM 프로그래밍)
nsIScriptableObject.h 파일에는 Add 함수에 대한 정의 부분만 들어가 있습니다. 내용을 잠시 보면
... 생략
/* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSISCRIPTABLEOBJECT \ NS_IMETHOD Add(PRInt32 a, PRInt32 b, PRInt32 *_retval);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSISCRIPTABLEOBJECT(_to) \ NS_IMETHOD Add(PRInt32 a, PRInt32 b, PRInt32 *_retval) { return _to Add(a, b, _retval); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSISCRIPTABLEOBJECT(_to) \ NS_IMETHOD Add(PRInt32 a, PRInt32 b, PRInt32 *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->Add(a, b, _retval); }
… 생략
위 와 같은 내용으로 이루어져 있습니다. Xpild이 자동으로 생성해주는 부분이기 때문에 많은 부분 생략되었습니다. 중요한 부분은 NS_DECL_NSISCRIPTABLEOBJECT 이라고 선언되어 있는 매크로 입니다. Xpidl이 자동으로 헤더 파일을 생성할 때 개발자가 구현을 쉽게 할 수 있도록 몇가지 매크로를 만들어 주는데요. NSISCRIPTABLEOBJECT은 개발자가 구현해야할 함수 원형을 매크로로 선언해놓은 부분입니다. 본 예에서는 함수가 하나밖에 없기 때문에 불필요해 보일 수도 있지만 실제로 헤더에 선언된 매크로들은 많은 편리함을 제공해줍니다.
이 헤더파일의 구현부를 작성해보도록 합시다. 구현 파일의 이름은 nsScriptableObject.h와 nsScriptableObject.cpp로 하겠습니다.
Step 1. nsScriptableObject 클래스를 만들고 Step 2. xpidl이 생성한 nsIScriptableObject 를 상속받습니다. Step 3. 그 다음에는 AddRef, Release, QueryInterface 함수를 구현해줍니다. (이 3함수들을 XPCOM 규약에 따르는 형식입니다.) Step 4. 그리고 마지막으로 Add 함수를 구현해줍니다.
nsScriptableObject.h 파일을 살펴보겠습니다. #include "nsIScriptableObject.h"
class nsScriptableObject : public nsIScriptableObject { public: nsScriptableObject(); virtual ~nsScriptableObject();
public: // native methods callable from JavaScript NS_DECL_NSISCRIPTABLEOBJECT
/////////////////////////////////////////////////////// // XPCOM Support ///////////////////////////////////////////////////////
NS_DECL_NSISCRIPTABLEOBJECT은 Add 함수의 원형이 들어있는 매크로 입니다. 그리고 아래는 AddRef, Release, QueryInterface 함수가 선언되어 있습니다.
nsScriptableObject.cpp 파일을 살펴보겠습니다. // AddRef, Release and QueryInterface are common methods and must // be implemented for any interface NS_IMETHODIMP_(nsrefcnt) nsScriptableObject::AddRef() { ++m_nRefCnt; return m_nRefCnt; }
// here nsScriptablePeer should return three interfaces it can be asked for by their iid's // static casts are necessary to ensure that correct pointer is returned NS_IMETHODIMP nsScriptableObject::QueryInterface(const nsIID& aIID, void** aInstancePtr) { if(!aInstancePtr) return NS_ERROR_NULL_POINTER;
NS_IMETHODIMP nsScriptableObject::Add(PRInt32 a, PRInt32 b, PRInt32 *_retval) { int nResult = a + b ;
*_retval = nResult ;
return NS_OK; }
AddRef, Release, QueryInterface 함수는 위 내용대로 구현하면 됩니다. 자세한 내용은 추후에 알아보도록 합니다.
Add 함수 구현부를 보면 인자로 a, b , _retval 이 있습니다. a와 b는 idl에서 선언해준 그대로의 형태로 되어 있으며, 반환값은 정수형 포인터로 _retval 로 지정되어 있는 것을 볼 수 있습니다. 일반 Function Call과 약간은 다른 형태로 보입니다.
nsIClassInfo 구현
JavaScript에서 Plug-in 함수를 호출을 허용하기 위해서는 nsIClassInfo를 상속받아야 합니다.
// We must implement nsIClassInfo because it signals the // Mozilla Security Manager to allow calls from JavaScript. #include "nsIClassInfo.h" class nsClassInfoMixin : public nsIClassInfo { // These flags are used by the DOM and security systems to signal that // JavaScript callers are allowed to call this object's scritable methods. NS_IMETHOD GetFlags(PRUint32 *aFlags) {*aFlags = nsIClassInfo::PLUGIN_OBJECT | nsIClassInfo::DOM_OBJECT; return NS_OK;} NS_IMETHOD GetImplementationLanguage(PRUint32 *aImplementationLanguage) {*aImplementationLanguage = nsIProgrammingLanguage::CPLUSPLUS; return NS_OK;} // The rest of the methods can safely return error codes... NS_IMETHOD GetInterfaces(PRUint32 *count, nsIID * **array) {return NS_ERROR_NOT_IMPLEMENTED;} NS_IMETHOD GetHelperForLanguage(PRUint32 language, nsISupports **_retval) {return NS_ERROR_NOT_IMPLEMENTED;} NS_IMETHOD GetContractID(char * *aContractID) {return NS_ERROR_NOT_IMPLEMENTED;} NS_IMETHOD GetClassDescription(char * *aClassDescription) {return NS_ERROR_NOT_IMPLEMENTED;} NS_IMETHOD GetClassID(nsCID * *aClassID) {return NS_ERROR_NOT_IMPLEMENTED;} NS_IMETHOD GetClassIDNoAlloc(nsCID *aClassIDNoAlloc) {return NS_ERROR_NOT_IMPLEMENTED;} };
#include "nsIScriptableObject.h" class nsScriptableObject : public nsIScriptableObject , public nsClassInfoMixin {
.. 생략
위 같이 nsClassInfoMixin 클래스를 작성해주시고, 구현한 nsScriptableObject 클래스에 상속을 시켜주세요. 이제 JavaScript에서 Plug-in에 있는 함수를 호출할 때 사용할 함수에 대한 구현이 완료되었습니다. 다음은 plug-in에서 ScriptableObject를 Firefox 브라우저에 넘겨주는 코드가 작성되어야 합니다.
CleanSample에서 GetValue 함수 추가 구현
이전에 작성하였던 CleanSample에서는 GetValue함수가 구현이 되어 있지 않습니다. 이 함수를 구현해야 Firefox 브라우저에게 ScriptableObject를 넘길 수가 있고, 그제서야 JavaScript에서 Plug-in 내부의 함수를 호출 할 수 있게 됩니다.
가장 먼저 fillPluginFunctionTable 함수에서 GetValue 함수 포인터를 넘겨주는 코드를 수정합니다. static NPError fillPluginFunctionTable(NPPluginFuncs* aNPPFuncs) { if(aNPPFuncs == NULL) return NPERR_INVALID_FUNCTABLE_ERROR;
// Set up the plugin function table that Netscape will use to // call us. Netscape needs to know about our version and size // and have a UniversalProcPointer for every function we implement.
그리고 다음으로 NPP_GetValue 함수를 구현합니다. 함수 내용은 대략적으로 Firefox가 ScriptableObject의 인스턴스를 요청처리와 Interface 요청 처리하는 코드로 구성되어 있습니다. NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR;
NPError rv = NPERR_NO_ERROR;
if (variable == NPPVpluginScriptableInstance) { // addref happens in getter, so we don't addref here nsScriptableObject * scriptablePeer = getScriptablePeer(); if (scriptablePeer) { *(nsScriptableObject **)value = scriptablePeer; } else { rv = NPERR_OUT_OF_MEMORY_ERROR; } }
ㅋ ㅑ ~ 에러없이 컴파일이 되는데 성공하셨나요? 저는 여기까지 오는데 무수한 삽질을 했습니다;; 마지막으로 Firefox에서 돌려보면서 결과를 보는 일만 남았습니다. 아래와 같은 HTML 페이지를 작성하신 다음에 %Firefox 설치 폴더%plugins 폴더에 NPPlugIn.dll 파일과 NPPlugIn.xpt 파일을 복사하신 다음 HTML 페이지를 Firefox로 열어보세요.
FireFox가 플러그인을 인식하기 위해서는 정확한 버전 정보를 생성해야 합니다. 이때 버전정보가 지켜야 할 규칙이 있는데 이를 명심하고 작성해야 합니다.
규칙1. 버전 정보는 English (US)로 설정되어야 합니다. 규칙2. Character Type은 Multilingual 로 설정되어야 합니다. 규칙3. FileEntents, MIMEType가 명시되어야 합니다.
리소스 추가 -> Version 을 한 뒤 Property 창에서 버전 정보를 English(US)로 설정합니다. 또한 프로젝트 세팅에서 Resource 탭에서 언어를 영어(미국)으로 설정합니다. 새로운 버전 블록을 추가할 때 English(US)로 설정하고 코드 페이지는 Multilingual로 설정합니다. 이 설정이 올바로 되어있는지 확인하기 위해서는 블록 코드가 "040904e4"로 설정되어 있는지 확인하면 됩니다.
FireFox가 플러그인을 인식하도록 하기 위해서는 MIME 타입을 반드시 버전 정보에 포함시켜야하는데, 이는 NPTest.rc 파일을 직접 수정하는 과정을 거쳐야 합니다.
NPTest.rc 예제 BLOCK "040904e4" BEGIN VALUE "Comments", "\0" VALUE "CompanyName", "ASP\0" VALUE "FileDescription", "NPTest\0" VALUE "FileExtents", "tst\0" VALUE "FileVersion", "1, 0, 0, 1\0" VALUE "InternalName", "NPTest\0" VALUE "LegalCopyright", "Copyright ⓒ 2006\0" VALUE "LegalTrademarks", "\0" VALUE "MIMEType", "application/test-plugin\0" VALUE "OriginalFilename", "NPTest.dll\0" VALUE "PrivateBuild", "\0" VALUE "ProductName", "ASP NPTest\0" VALUE "ProductVersion", "1, 0, 0, 1\0" VALUE "SpecialBuild", "\0" END
Step 8) 플러그인을 로드하는 HTML 작성
<embed> 태그를 이용해서 플러그인을 로드 할 수 있습니다. 위 예제에서는 type 속성을 명시해줌으로써 플러그인을 로드 할 수 있습니다.
Test.html 예제 <html> <body>
<center><h1>Basic Plugin Example for Mozilla Test Case</h1></center>
This test case is to demonstrate the Basic Plugin example. You should see the plugin window with the black frame aroung it and the browser user agent string which plugin draws inside the window. <br><br>
</html> </body> Embed 태그의 type 속성을 버전에서 정해준 MIME 타입으로 설정해둔 것을 볼 수 있습니다. 위의 HTML 파일을 FireFox로 불러오면 플러그인이 로드된다. 테스트를 위해서 플러그인 로드시 MessageBox를 띄우는 코드를 작성한 후 테스트 합니다.
Step 9) FireFox에서 불러오기
NPTest.cpp 수정 부분 NPError OSCALL NP_Initialize(NPNetscapeFuncs* aNPNFuncs) { AfxMessageBox( "hi" ) ; return NPERR_NO_ERROR; }
NP_Initialize에 AfxMessageBox를 불러오는 코드를 작성해봅니다. MFC를 사용하기 위해서는 프로젝트 설정 정보에서 Using MFC로 설정해야 하며, 다음과 같은 헤더 정보를 포함해야 합니다.
MFC를 사용하기 위한 헤더 설정 #include <afxwin.h> // MFC 핵심 및 표준 구성 요소 #include <afxext.h> // MFC 익스텐션 #include <afxdisp.h> // MFC 자동화 클래스
이제 컴파일 한 후 결과 파일인 NPTest.dll 파일을 파이어폭스가 설치된 폴더에서 plugin 폴더에 복사한 후 위에서 작성한 test.html 파일을 불러오세요.
그림 1 Hi?
PlugIn이 실행되는걸 직접 확인하셨나요?
맨땅에서부터 정말로 실행되는 단계까지 직접 해보신 기분이 어떤가요? 플러그인 만드는 거 별거 아닌 것 같습니다. 여기에 자신의 아이디어를 적용시켜보세요!