上次写到如何用vb跟sas交互,不过vb用来开发运行效率较高的系统绝不是理想选择
下面就介绍一下如何用vc通过com方式跟sas交互
其实也没有什么,只有知道vc调用com的方式然后在参照我blog的上面文章,不用我说也知道,
所以我这篇文章面对的“客户”是菜鸟级程序员
第一步,当然是把这个com的类型库导入,不然vc编译器不认识你的数据类型,so so..,导入语法
#import "c:\program files\sas\shared files\integration technologies\sas.tlb"
上面就是你sas类型库所在的目录了
第二步,微软告诉我,要调用com必须先初始化com环境,最后当前是清除com环境,所以要写下下面代码
coinitialize(null);
/*
n多代码在这中间
*/
...
couninitialize();
第三步,当然是生成com对象的实例了,生成com对象实例的方法有n种,但下面这种最容易,也最好使
首先,要获得com对象的clsid
clsid clsid;
clsidfromprogid(olestr("sas的com对象,如sas.workspace"),&clsid);
然后,利用这个clsid,通过智能指针就可以生成对象了,如下
ccomptr<iworkspace> _sas;
_sas.cocreateinstance(clsid);
ok,对象已经建好了,可以调用该对象的方法了,如
_sas->close();
看官,明白了把 ,噢,忘了,要包含头文件#include <atlbase.h>,不然也会报错的
好了,下面给个例子让你看看吧
下面这个类封装了sas.workspace的基本功能
#import "c:\program files\sas\shared files\integration technologies\sas.tlb"
using namespace sas;
class csaspool{
public:
ccomptr<iworkspace> _sas;
int currrunthreadnum;
bool state;
clsid clsid;
csaspool(bool active,clsid clsid)
{
this->clsid=clsid;
if (active){
_sas.cocreateinstance(clsid);
(_sas->languageservice)->async=true;
state=true;
}else{
_sas=null;
state=false;
}
currrunthreadnum=0;
}
void start_sas() {
if (!state) {
_sas.cocreateinstance(clsid);
_sas->languageservice->async=true;
}
state=true;
}
void exec(char * command) {
_sas->languageservice->submit(command);
}
void close(){
_sas->close();
}
};
然后用下面这段代码调用就是了
#include "stdafx.h"
#include <atlbase.h>
#include "csaspool.h"
int main(int argc, char* argv[])
{
coinitialize(null);
clsid clsid;
clsidfromprogid(olestr("sas.workspace"),&clsid);
csaspool sas=csaspool(true,clsid);
sas.exec("data _null_;file 'd:\\1.txt';put 'ok';run;");
sas.close();
couninitialize();
}
over了,这段代码调用最后的结果会在你的d盘生成一个1.txt文件,然后呢这个文件里会包含一个ok的字眼
完是完了,但是有个特别隐秘的bug包含在程序中,就是那个智能指针的使用
众所周知,智能指针给我们封装了一个完美的指针,以致于我们根本不必关注什么++ ——的引用关系
但是
我们的智能指针_sas生命周期的结束是在
couninitialize()之后,coinitialize所开的环境在couninitialize()后已经被
关闭,而_sas此时发生析构,可能会导致某些问题,so so ,上面调用的代码稍微改一下,就万事大吉了
#include "stdafx.h"
#include <atlbase.h>
#include "csaspool.h"
int main(int argc, char* argv[])
{
coinitialize(null);
clsid clsid;
clsidfromprogid(olestr("sas.workspace"),&clsid);
{
csaspool sas=csaspool(true,clsid);
sas.exec("data _null_;file 'd:\\1.txt';put 'ok';run;");
sas.close();
}
couninitialize();
}
这次可是真正完了,没什么说的了