同学们下午好, 在前一篇教程中我们已经了解了基本的SWIG创建SWC的过程, 今天我捣鼓了大半天研究了如何调用C++的类, 接下来说说过程吧.
首先编写C++类, 分别是example.h和example.cpp, 如下:
/**example.h*/
class TestCC
{
public:
TestCC(double, double);
double x, y;
virtual double add(void);
virtual void set(double, double);
void copyTo(TestCC*);
};
#include "example.h"
/**example.cpp*/
TestCC::TestCC(double v1, double v2)
{
x = v1;
y = v2;
}
void TestCC::copyTo(TestCC* t)
{
t->x = x;
t->y = y;
}
double TestCC::add(void)
{
return x+y;
}
void TestCC::set(double v1, double v2)
{
x = v1;
y = v2;
}
代码很简单, 相信不需要怎么说明了吧.
接下来就是打包了. 我们需要改一下swig的接口文件, 就像下面那样:
#ifdef SWIG
%module AddExample
%{
#include "example.h"
%}
%include "example.h"
#else
#include "example.h"
#endif
相应的MakeFile文件也做相应的修改:
all: check
@echo "-------- PassingData --------"
@echo "-> Generate SWIG wrappers around the functions in the library"
"$(FLASCC)/usr/bin/swig" -c++ -as3 -module AddExample -outdir . -ignoremissing -o AddExample_wrapper.cpp example.i
@echo "-> Compile the SWIG wrapper to ABC"
$(AS3COMPILERARGS) -abcfuture -AS3 -import $(call nativepath,$(FLASCC)/usr/lib/builtin.abc) -import $(call nativepath,$(FLASCC)/usr/lib/playerglobal.abc) AddExample.as
@echo "-> Compile the library into a SWC"
"$(FLASCC)/usr/bin/g++" $(BASE_CFLAGS) AddExample.abc AddExample_wrapper.cpp example.cpp main.cpp -emit-swc=sample.add -o add.swc
include ../Makefile.common
clean:
rm -f *_wrapper.c *.swc *.as *.abc
修改了什么地方呢? 只是在第4行加了一个" -c++"而已啦, 不加的话会报一个“Warning 301: class keyword used, but not in C++ mode”的错误, 所以同学们加上吧.
接下来执行make命令吧, 看看是不是生成了add.swc文件了呢?
最后还是在AS中进行测试:
package
{
import flash.display.Sprite;
import sample.add.CModule;
public class UnitTest extends Sprite
{
public function UnitTest()
{
CModule.startAsync(this);
var a:TestCC = TestCC.create(10, 10);
trace(a.add());
a.set(20, 20);
trace(a.add());
var t:TestCC = TestCC.create(10, 10);
t.copyTo(a.swigCPtr);
trace(a.add());
}
}
}
猜猜输出是什么? 是的, 如你们所预期的! 实验成功
20
40
20