Tuesday, September 25, 2007

F# and ArcObjects

Interested in programming with ArcObject using F#? It's easy!

Start fsi referencing the appropriate ArcObjects assemblies:
C:\>fsi -I C:\ArcGis\DotNet -r ESRI.ArcGIS.System.dll -r ESRI.ArcGIS.DataSourcesGDB.dll -r ESRI.ArcGIS.Geodatabase.dll

Now you can open some ArcObjects namespaces:
> open ESRI.ArcGIS.esriSystem;;

> open ESRI.ArcGIS.DataSourcesGDB;;

> open ESRI.ArcGIS.Geodatabase;;

Next, we need to initialize our license:
> let aoi = new AoInitializeClass();;

val aoi : AoInitializeClass

> aoi.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcView);;

val it : esriLicenseStatus = esriLicenseCheckedOut

Then we can connect to our geodatabase:
> let workspaceString = "user=MyUserName;password=MyPassword;server=MyServer;instance=MyInstance;version=SDE.DEFAULT";;

val workspaceString : string

> let fact = new SdeWorkspaceFactoryClass();;

val fact : SdeWorkspaceFactoryClass

> let ws = fact.OpenFromString(workspaceString, 0);;

val ws : IWorkspace

> let featureWs = (box ws) :?> IFeatureWorkspace;;

val featureWs : IFeatureWorkspace

Notice that we have to first box our Workspace object before we can cast it to the IFeatureWorkspace interface. I believe that this has to do with explicit member implementation, but I could be wrong.

Want to get a specific feature? OK:
> let fc = featureWs.OpenFeatureClass("MyFeatureClass");;

val fc : IFeatureClass

> fc.GetFeature(1684597);;

val it : IFeature = System.__ComObject

And so on...

As you can see, F# has no problem working with ArcObjects. Throw in the Interactive Console and you have a very attractive platform for programming with ArcObjects.


Anonymous said...

Fantastic! I'm developing a standalone GIS processing tool in F# now.

A word of warning to 64 bit Windows users: ArcGIS libraries are x86 only. Be sure to use "fsc --platform:x86".

Kirk said...

Thanks for posting this. Have a follow up question here: