从 ug nx二次开发程序中调用宏

Macro,宏

UG NX中,宏的作用是类似于鼠标点击器,完全是一一对应于菜单项目,回放的时候也是一项一项地调用菜单项。这个跟“操作记录 Journal”有本质不同,操作记录是自动将你的操作转换成对应的API。

因此,如果只是做简单地自动化,宏的兼容性比Journal好:不是所有操作都能转换成Journal,但只要是你能做出来的操作,都可以录制为宏。但显然仅仅依靠界面上能“点”的这些按钮,做不了什么黑科技工作。

从二次开发程序中运行宏

本来是没有官方API的,但架不住有人研究,还是有一个曲线救国的办法:

Yes, you can do this with the undocumented function "MACRO_playback_from_usertool" from libugui.dll, which you can access using UF_load_library. UF_load_library will give you a function pointer which you can then invoke with the name of your macro as the argument. It's rather complicated and should be only used as a last resort (i.e. you absolutely must do this and there's no way to get around it), because, well, it's an undocumented function! You never know if the NX devs throw it out in the next version, or make you PC spontaneously combust, or something.

基本步骤: 1. 用UF_load_library得到MACRO_playback_from_usertool的地址 2. 调用MACRO_playback_from_usertool指向宏文件

不幸的是,由于是“from_usertool”,这个函数是无法从externel模式调用的,只能是从某个用户出口来调用,也就是调用时UG的窗口必须开着,这就没办法了。所以这个办法也不是特别实用,聊胜于无。

另外一个问题是,即使以internal模式运行,宏的执行也不是实时的,而是需要等到二次开发的函数执行完毕之后,才会实际开始调用——估计是因为调用过程中程序GUI界面是锁定的吧,这一点有时候特别烦人:

比如,打开一个模型,对模型执行一个宏,再关闭文件,这个功能是实现不了的。原因是函数执行完毕之前,宏没有被实际调用(即使可以调用,此时程序界面也不会更新,所以有可能连相应菜单项都不存在)。等到函数运行完了,文件已经被关掉了,这时候再运行宏,显然是不行的。

MACRO_playback_from_usertool得到的指针是一个void指针,需要做一个强制类型转换。下面是一个例子。需要注意UF_load_library的参数用法和普通指针转换为函数指针的写法。

main.cpp
#include <uf.h>
#include <uf_part.h>
 
#include <string>
#include <windows.h>
 
extern "C" DllExport void ufusr(char *p, int * ret, int pp)
{
        UF_initialize();
 
        const std::string inputFilePath="C:\\Documents\\model3.prt";
        const std::string outputFilePath="C:\\Documents\\model3333334.prt";
 
        const std::string runMacroFunctionName="MACRO_playback_from_usertool";
        UF_load_f_p_t runMacroFunctionPtrT=NULL;
 
        int r = UF_load_library("C:\\Program Files\\UGS\\NX 6.0\\UGII\\libugui.dll","?MACRO_playback_from_usertool@@YAXPBD@Z", &runMacroFunctionPtrT);
 
        void (*runMacroFunctionPtr)(char *) = (void (*)(char*))runMacroFunctionPtrT;
 
        tag_t prtFile=NULL_TAG;
        UF_PART_load_status_t openErr;
        UF_PART_open(inputFilePath.c_str(), &prtFile, &openErr);
        Sleep(3000);
        //runMacroFunctionPtr("C:\\Documents\\wrl.macro");
        if(prtFile != NULL_TAG)
        {
                UF_PART_save_as(outputFilePath.c_str());
 
                runMacroFunctionPtr("C:\\Documents\\wrl.macro");
                Sleep(3000);
                //UF_PART_close(prtFile, 1, 1);
        }
 
        UF_terminate();
}
  • 最后更改: 2019/07/26 08:30