xarial / xcad

Framework for developing CAD applications for SOLIDWORKS, including add-ins, stand-alone applications, macro features, property manager pages, etc.
https://xcad.net
MIT License
131 stars 28 forks source link

Exception thrown when trying to convert from Solidworks sketch to ISwSketch2d #85

Open flycast opened 2 years ago

flycast commented 2 years ago

I need to convert a Solidworks sketch to an XCad.Solidworks.ISwSketch2D object.

As I understand I can use a pointer to a Solidworks Sketch to create a ISWxxxxxxx entity:

   public SketchInventory(ISwApplication swApplication, ISketch sketch)
    {
        _xApp = swApplication;
        _swApp = swApplication;
        var test = swApplication.Documents.Active.CreateObjectFromDispatch<ISwSketch2D>(sketch);

Only when I do this I get:

Exception thrown: 'System.InvalidCastException' in Xarial.XCad.SolidWorks.dll Exception thrown: 'System.Reflection.TargetInvocationException' in mscorlib.dll

Is this a bug or am I not doing things right?

Summary: I need to get a ISwXXXXXX object from a pointer to a Solidworks object. How?

artem1t commented 2 years ago

Your code is correct (it works fine for me). Just make sure that the ISketch is not a 3DSketch (in this case you need to use ISwSketch3D) and not null. Or just use ISwSketchBase for the common interface.

flycast commented 2 years ago

Thank you. These two versions just worked for me.

ISwApplication xCadSwApp = _application as ISwApplication;
var test = xCadSwApp.CreateObjectFromDispatch<ISwSketch2D>(sketch, xCadSwApp.Documents.Active);
var test1 = xCadSwApp.Documents.Active.CreateObjectFromDispatch<ISwSketch2D>(sketch);
flycast commented 2 years ago

Not sure if this is an issue or not. This is now working fine when I get an ISketch object coming from a Sketch in the Solidworks feature tree (as noted above). Now I am trying to get the ISwSketch2D in the same way but using the ISketch from the ISketchBlockDefinition:

var blockInstance = node.Feature.GetSpecificFeature2() as ISketchBlockInstance;
var blockDefinition = blockInstance.Definition as ISketchBlockDefinition;
var blockSketch = blockDefinition.GetSketch();
sketchFromDispatch = xCadSwApp.CreateObjectFromDispatch<ISwSketch2D>(blockSketch, xCadSwApp.Documents.Active);

It seems I am getting two different objects. If I get the ISketch from a sketch feature I get a com object. If I get an ISketch from ISketchBlockDefinition::GetSketch() I get a SketchClass. When I use the SketchClass it is not a pointer to the com object so the CreateObjectFromDispatch fails.