Site Tools


Passing Arrays from RhinoScript to .NET

Version: Rhino 4
Summary: Demonstrates how to pass VBScript SafeArrays to from RhinoScript to .NET.

Question

I am writing a .NET plug-in that extends RhinoScript. I've used the information on this page to get started:

SdkExtendRhinoScript

I would like to write a function in .NET, that I could call from RhinoScript, that I could pass an array of 3-D point coordinates, manipulate these coordinates, and then pass the modified values back to RhinoScript. I am not sure how to proceed. Any help would be appreciated.

Answer

The stumbling block here is that when a SafeArray passed from VBScript, it is marshalled as a .NET object. Thus, you must cast the object to a .NET Array.

The following example code demonstrates how you can do this.

VB.NET

Public Function TweakPoints(ByVal var As Object) As Object
  ' Default return value
  TweakPoints = Nothing
 
  ' The safearray passed from VBScript is marshalled as a .NET object. 
  ' So, try to cast the object argument as an array.
  Dim arr As Array = TryCast(var, Array)
  If arr Is Nothing Then Exit Function
 
  ' Declare our results array
  Dim rc As New ArrayList()
 
  ' Loop through all point arrays
  Dim i As Integer = 0
  For i = 0 To UBound(arr)
    ' The safearray passed from VBScript is marshalled as a .NET object. 
    ' So, try to cast the object argument as an array.
    Dim pt As Array = TryCast(arr.GetValue(i), Array)
    If (pt IsNot Nothing) AndAlso (pt.Length = 3) Then
      ' Extract the point coordinate values
      Dim x As Double = Convert.ToDouble(pt.GetValue(0))
      Dim y As Double = Convert.ToDouble(pt.GetValue(1))
      Dim z As Double = Convert.ToDouble(pt.GetValue(2))
 
      '
      ' TODO: do some kind of point manipulation here....
      '

      ' Declare an array for the new point
      Dim point As New ArrayList()
 
      ' Add the updated coordinates to the array
      point.Add(x)
      point.Add(y)
      point.Add(z)
 
      ' Add the array to the results array as an object
      rc.Add(point.ToArray())
    End If
  Next
 
  ' Return our results array
  TweakPoints = rc.ToArray()
End Function
developer/dotnettorhinoscript3.txt ยท Last modified: 2015/09/14 (external edit)