我正在使用IronPython 2.7.9在Visual Studio2017上创建自己的WPF应用程序。我想连接到激活的Solidworks应用程序,并将自定义属性值作为字符串传递到激活的零件或组件。
WPF应用程序将检查哪个文件是打开的。在此之后,它将更新为已作为自定义属性写入应用程序的应用程序值。通过修改这些值并保存,我会将它们写入Solidworks零件或组件。
我的第一步是创建到正在运行的Solidworks的连接,获取活动文档文件名并将其显示在我的应用程序的textbox上。
我接触到的第一个问题是,没有关于连接到IronPython上的Solidworks应用程序的正确方法的信息。实际上,IronPython不支持Solidworks API中引用的早期绑定。Solidworks自带了自己的API DLL文件。
我已经使用了Visual Studio 2017 Ironpython WPF应用程序项目。我已经在解决方案资源管理器中添加了\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#).
发布于 2019-03-26 20:53:41
我认为应该是这样的:
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
https://stackoverflow.com/questions/55343521
复制相似问题