An FYI to other C# developers: How to access the NativeObject if using C# to build an Inventor Add-in

An FYI to other C# developers: How to access the NativeObject if using C# to build an Inventor Add-in

rwemmerLHAEW
Participant Participant
96 Views
1 Reply
Message 1 of 2

An FYI to other C# developers: How to access the NativeObject if using C# to build an Inventor Add-in

rwemmerLHAEW
Participant
Participant

I struggled with an issue for awhile. So I wanted to share the solution. I needed to access the NativeObject property for an Edge. This is easily done with VB.NET, however, it is not quite as easy if you are using C#, as the NativeObject is a private property.  In my use case, I needed the NativeObject for an edge in order to add it to a sketch. The solution ultimately required the use of reflection. Here is a simplified approach for accomplishing the goal. I just wanted to share this in the event that it helps someone else.  Here is a simple approximation of the solution:

 

 

 

 

 

using System.Reflection;

public object GetNativeObject(Edge selectedEdge)
{
      // First I tried to get the source edge using GetSourceEdge()
      Edge sourceEdge = selectedEdge.GetSourceEdge();
      if (sourceEdge != null)
      {
          return sourceEdge;
      }
      // For my use case,  sourceEdge would result in being null.
      // Therefore, I used reflection to get the NativeObject
      object nativeObject = selectedEdge.GetType().InvokeMember(
             "NativeObject",
             BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
             null,
             selectedEdge,
             null);
      if (nativeObject is Edge nativeEdge)
      {
         return nativeEdge;
      }
      return null;
}

 

 

 

 

 

0 Likes
97 Views
1 Reply
Reply (1)
Message 2 of 2

jjstr8
Collaborator
Collaborator

If your edge selection is from an assembly, then it's actually an EdgeProxy. I don't know what your call to GetNativeObject is, but try adding this and see if it returns a Edge. EdgeProxy derives from Edge, so it can be passed into a method that wants an Edge.

 

public object GetNativeObject(Edge selectedEdge)
{            
    if (selectedEdge is EdgeProxy edgeProxy)
    {
        return edgeProxy.NativeObject;
    }
...

 

0 Likes