我正在使用IronPython 2.7.9在Visual Studio 2017上创建自己的WPF应用程序。我想连接到活动的Solidworks应用程序并将自定义属性值作为字符串传递给活动部件或程序集。
WPF应用程序将检查打开的文件。在此之后,它会更新已作为自定义属性写入应用程序的应用程序值。通过修改这些值并保存,我会将它们写入Solidworks零件或装配体。
我的第一步是创建与正在运行的Solidworks的连接,获取活动文档文件名并在文本框上的应用程序中显示它。
我接触到的第一个问题是没有关于在IronPython上连接到Solidworks应用程序的正确方法的信息。实际上,IronPython不支持Solidworks API中引用的早期绑定。 Solidworks自带API DLL文件。
我使用过Visual Studio 2017 Ironpython WPF应用程序项目。我在Solution explorer中添加了\SOLIDWORKS\api\redist
的搜索路径。之后我启动了代码:
python
import clr
clr.AddReference("SldWorks.Interop.sldworks")
import SldWorks.Interop.sldworks as SldWorks
swApp = SldWorks.SldWorks # Get from here the active document
swModel = SldWorks.ModelDoc2 # Get string through GetTitle() from here
print(swModel.GetTitle(swApp.ActiveDoc))
我希望这可以从活动的Solidworks会话中获得一个活动的文档标题。然后打印出来。
当使用定义的sys.path.append
运行IronPython 2.7交互式窗口时,最后一行给出了TypeError: expected IModelDoc2, got getset_descriptor
。
更新:到目前为止,我已经尝试过这种类型的代码了。创建一个继承ModelDoc2类属性的类:
import clr
import sys
import System
sys.path.append(r"C:\Program Files\SOLIDWORKS Corp\SOLIDWORKS\api\redist")
clr.AddReference("SolidWorks.Interop.sldworks")
import SolidWorks.Interop.sldworks as SldWorks
class ModelDoc(SldWorks.ModelDoc2):
def getActiveDocumentTitle(self):
self.str = SldWorks.ModelDoc2.GetTitle(SldWorks.IModelDoc2)
return self.str
swApp = ModelDoc()
print(swApp.getActiveDocumentTitle())
问题仍然是一样的。我明白了
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "<string>", line 3, in getActiveDocumentTitle
TypeError: expected IModelDoc2, got type
SOLIDWORKS是一个基于COM的API,它使用:
Interfaces
Interface inheritance
Factory methods to return interfaces on existing and new objects
Casting between interfaces through:
QueryInterface (C++), which returns a pointer to a specified interface on an object to which a client currently holds an interface pointer.
direct assignment (VB/VB.NET).
the is/as reserved words (C#).
我认为它应该是这样的:
import clr
import sys
import System
sys.path.append(r"C:\Program Files\SOLIDWORKS Corp\SOLIDWORKS\api\redist")
clr.AddReference("SolidWorks.Interop.sldworks")
import SolidWorks.Interop.sldworks as SldWorks
swApp = System.Runtime.InteropServices.Marshal.GetActiveObject("SldWorks.Application")
swModel = swApp.ActiveDoc
print(swModel.GetTitle())
这是C#上类似的工作代码
SldWorks swApp;
swApp = (SldWorks)System.Runtime.InteropServices.Marshal.GetActiveObject("SldWorks.Application");
//swApp = (SldWorks)Activator.CreateInstance(System.Type.GetTypeFromProgID("SldWorks.Application"));
ModelDoc2 doc = swApp.ActiveDoc;
var str = doc.GetTitle();
Console.WriteLine(str);
另请参阅此文章,其中包含有关从独立应用程序访问SolidWorks的有用信息:https://forum.solidworks.com/thread/215594