Chapter 9: Writing Add-ins in C++/CLI


In the previous chapter, we briefly looked at how Add-ins can call exported functions from NativeCode. While many NativeCode functions can be accessed using PInvoke, some C/C++ features cannot. Constructors are one such example, and the scenario covered in this chapter falls into that category.

 

As mentioned in the initial Chapter, MicroStation Add-ins, support two development frameworks. Chapter 2 introduced how to create elements in both frameworks. In real-world projects, however, you may sometimes need to move elements from one framework to the other. Unfortunately, the Add-ins API does not provide a direct method for doing this.

 

If you look more closely, you will find that both frameworks expose access to the NativeCode objects used to create and manage elements. In the COM framework, the MdlElementRef and MdlElementDescrP members provide access to the underlying ElementRefP and MSElementDescrP pointers.

The MdlCreateElementFromElementDescrP function can then create a COM Element from an MSElementDescrP.

 

In the newer development framework, the Element class exposes an ElementHandle property that provides access to the underlying NativeCode object. It also includes the protected InitializeFromElementHandle method, which can create an element instance from an ElementHandle.

On the NativeCode side, ElementHandle supports constructors and methods that work with both ElementRefP and MSElementDescrP.

 

Because of this, ElementHandle can act as a bridge between the two programming frameworks. Using PInvoke alone would require multiple exported conversion functions and additional pointer handling on the Add-ins side. In contrast, C++/CLI allows managed and unmanaged code to work together in the same block of code. This makes the conversion process much simpler, allowing both conversion directions to be handled through a single, easy-to-use function.

 

Before working through the examples in this chapter, make sure that the MicroStation SDK is installed on your development machine. If you have not yet obtained the SDK, refer to the linked Wiki article for download and installation instructions.

 

 

Let's implement these two transformation functions step by step.

 

1. Create directory SampleMixed

 

Create a new directory as shown below

D:\CS\Chapter9\SampleMixed

 

 

2. Create header SampleMixed.h

 

Launch a text editor (you can also use Visual Studio), enter the following text, and save it as D:\CS\Chapter9\SampleMixed\SampleMixed.h

 

This header file contains the declaration of the class that implements the element conversion functionality. It also defines a class named ElementDerive, which inherits from Bentley.DgnPlatformNET.Elements.Element and provides access to functionality needed during the conversion process.

 

#pragma once

#pragma managed

#using <Bentley.MicroStation.dll>
#using <Bentley.GeometryNET.Structs.dll>
#using <Bentley.DgnPlatformNET.dll>
#using <Bentley.Interop.MicroStationDGN.dll>

#include <Mstn\MdlApi\MdlApi.h>
#include <Mstn\ISessionMgr.h>
#include <Mstn\MdlApi\mselems.h>
#include <msclr/gcroot.h>
#include <Mstn\MdlApi\dloadlib.h>

USING_NAMESPACE_BENTLEY_DGNPLATFORM;
USING_NAMESPACE_BENTLEY_MSTNPLATFORM;
USING_NAMESPACE_BENTLEY_MSTNPLATFORM_ELEMENT;
using namespace msclr;
namespace GeoNet = Bentley::GeometryNET;
namespace DgnNetEle = Bentley::DgnPlatformNET::Elements;
namespace InteropMstn = Bentley::Interop::MicroStationDGN;

namespace SampleMixed
{
	public ref class ElementDerive :public DgnNetEle::Element
	{
	public:
		ElementDerive(ElementHandleP);
	};

	public ref class ElementOperation
	{
	public:
		static DgnNetEle::Element^  ConvertToDgnNetEle(InteropMstn::Element^ ele);
		
		static InteropMstn::Element^ ElementOperation::ConvertToInteropEle
		                             (DgnNetEle::Element^ ele);
	};
}

 

3. Create SampleMixed.cpp

 

Launch a text editor (you can also use Visual Studio), enter the following code, and save it as D:\CS\Chapter9\SampleMixed\SampleMixed.cpp

 

This file contains the implementation of ElementDerive and the two conversion functions.

 

using namespace System::Reflection;

#include <Mstn\MdlApi\mselemen.fdf>
#include <vcclr.h>
#include "SampleMixed.h"


namespace SampleMixed
{

[assembly:AssemblyDelaySignAttribute(false)];

	ElementDerive::ElementDerive(ElementHandleP eehp)
	{
		InitializeFromElementHandle(*eehp);
	}

	DgnNetEle::Element^ ElementOperation::ConvertToDgnNetEle(InteropMstn::Element^ ele)
	{
		ElementDerive^ rtnEle = nullptr;
		if ((long)ele->MdlElementRef() != 0)
		{
			EditElementHandle eeh((ElementRefP)(void*)ele->MdlElementRef(), 
			                     (DgnModelRefP)(void*)ele->ModelReference->MdlModelRefP());
			rtnEle = gcnew ElementDerive(&eeh);
			return rtnEle;
		}
		MSElementDescrP elmdscrP = (MSElementDescrP)(void*)ele->MdlElementDescrP(false);
		EditElementHandle eeh(elmdscrP, true, false, 
			                 (DgnModelRefP)(void*)ele->ModelReference->MdlModelRefP());
		rtnEle = gcnew ElementDerive(&eeh);
		return rtnEle;
	}

	InteropMstn::Element^ ElementOperation::ConvertToInteropEle(DgnNetEle::Element^ ele)
	{
		cli::pin_ptr<unsigned char> pb = &(ele->ElementHandle[0]);
		ElementHandleP ehp = reinterpret_cast<ElementHandleP>(pb);
		InteropMstn::Application^ msApp = Bentley::MstnPlatformNET::InteropServices::Utilities::ComApp;
		MSElementDescrP elmdscrp = const_cast<MSElementDescrP>(ehp->GetElementDescrCP());
		long long* lp = reinterpret_cast<long long*>(&*elmdscrp);
		long long elmDscrp = *reinterpret_cast<long long*>(&lp);
		InteropMstn::Element^ rtnEle = msApp->MdlCreateElementFromElementDescrP(elmDscrp);
		return rtnEle;
	}
}

 

ConvertToDgnNetEle handles the conversion of an element from the COM framework to the newer .NET framework. The function first obtains either an ElementRefP or MSElementDescrP pointer through the COM element's MdlElementRef or MdlElementDescrP members. These pointers are then used to construct an unmanaged EditElementHandle object.

The constructor of ElementDerive requires a pointer to an ElementHandle, and since EditElementHandle is derived from ElementHandle, it can be passed directly to the constructor. This allows an ElementDerive instance to be created and initialized from the COM element before being returned to the caller.

 

ConvertToInteropEle performs the conversion in the opposite direction, from the .NET framework back to the COM framework. The function first obtains a pointer to the element's ElementHandle through the ElementHandle property exposed by the .NET element.

Because .NET objects can be relocated during garbage collection, the C++/CLI cli::pin_ptr type is used to temporarily pin the ElementHandle in memory. This prevents the object from being moved while its native pointer is being accessed, ensuring that the pointer remains valid throughout the conversion process.

Once the ElementHandle is available, the function retrieves the associated MSElementDescrP pointer. This pointer is then passed to the MdlCreateElementFromElementDescrP method of Bentley.Interop.MicroStationDGN.Application, which creates and returns the corresponding COM Element.

By using ElementHandle as an intermediate object, the code can seamlessly convert elements between the COM and .NET programming frameworks while keeping the implementation simple and easy to understand.

 

 

4. Create SampleMixed.mke

 

Launch a text editor (you can also use Visual Studio), enter the following text, and save it as D:\CS\Chapter9\SampleMixed\SampleMixed.mke

 

This file is used by the bmake tool under the SDK to compile the source code. To know more about the format of the .mke file, check wiki Detailed explanation of mke file.

 

BUILD_USING_VS2022 = 1

DemoSrcDir   = $(_MakeFilePath)
PolicyFile = MicroStationPolicy.mki
appName    = SampleMixed
ASSEMBLY_NAME       = $(appName)
RIGHTSCOMPLIANT     = false

MDLMKI = $(MSMDE)mki/

mdlLibs = $(MSMDE)library/

%include        mdl.mki

outputDir = $(MS)Mdlapps/

always:
    ~mkdir $(o)

objList = $(o)SampleMixed$(oext)

%include compileForCLRStart.mki

CCompDebugOptions = $(CCompDebugOffSwitch)

CCompDebugOptions =% $[CCompDebugDefault]

CCompOpts + -AI$(MS)Assemblies -AI$(MS)Assemblies/ECFramework -AI$(MS) -AI$(o)

dirToSearch = ${msPrivInc}

$(o)SampleMixed$(oext) : $(baseDir)SampleMixed.cpp

%include compileForCLRStop.mki

DLM_OBJECT_DEST         = $(o)
DLM_NAME                = $(appname)
RIGHTSCOMPLIANT         = true
DLM_DEST                = $(outputDir)
DLM_OBJECT_FILES        = $(objList)
DLM_NO_DEF              = 1
DLM_NO_DLS              = 1
DLM_NO_IMPLIB           = 1
DLM_NO_SIGN = 1

ASSEMBLY_VERSION        = 1.0.0.0
ASSEMBLY_TITLE          = $(appName)
ASSEMBLY_DESCRIPTION    = MixedMode Test Application
ASSEMBLY_PRODUCT_NAME   = $(appName)
ASSEMBLY_FILE_VERSION   = 1.0.0.0
ASSEMBLY_COMPANY_NAME   = Bentley Systems
ASSEMBLY_COPYRIGHT      = Copyright: (c) 2019 Bentley Systems, Incorporated. All rights reserved.

LINKER_LIBRARIES            + $(mdlLibs)BentleyAllocator.lib
LINKER_LIBRARIES            + $(mdlLibs)DgnPlatform.lib

%include linkMixedAssembly.mki

 

 

You can download the SampleMixed files here and create a DLL.

 

 

5. Create SampleMixed.DLL

 

 

   CD D:\CS\Chapter9\SampleMixed\SampleMixed\

 

       Bmake +a SampleMixed.mke

 

       C:\Program Files\Bentley\MicroStation 2026\MicroStation\Mdlapps\

 

 

 

6. Modify CsAddins9 project

 

At this point, our two conversion functions are now encapsulated. Next, let's verify them in the csAddins9 project.

 

 

csAddins9 CreateElement TestConvertToDgnNetEle

csAddins9 CreateElement TestConvertToInteropEle

Specify their handler function as

csAddins9.CreateElement.TestConvertToDgnNetEle

csAddins9.CreateElement.TestConvertToInteropEle

 

 

public static void TestConvertToDgnNetEle(string unparsed)
{
    BIM.Application app = Bentley.MstnPlatformNET.InteropServices.Utilities.ComApp;
    BIM.Point3d ptStart = app.Point3dZero();
    BIM.Point3d ptEnd = ptStart;
    ptStart.X = 10;
    BIM.LineElement lineEle = app.CreateLineElement2(null, ref ptStart, ref ptEnd);
    Element ele = SampleMixed.ElementOperation.ConvertToDgnNetEle(lineEle);
    ElementPropertiesSetter elePropSetter = new ElementPropertiesSetter();
    elePropSetter.SetColor(1);
    elePropSetter.SetWeight(2);
    elePropSetter.Apply(ele);
    ele.AddToModel();
}

public static void TestConvertToInteropEle(string unparsed)
{
    DgnModel dgnModel = Session.Instance.GetActiveDgnModel();
    ModelInfo modelInfo = dgnModel.GetModelInfo();
    DPoint3d[] ptArr = new DPoint3d[5];
    ptArr[0] = new DPoint3d(0 * UorPerMas, 10 * UorPerMas, 0 * UorPerMas);
    ptArr[1] = new DPoint3d(1 * UorPerMas, 12 * UorPerMas, 0 * UorPerMas);
    ptArr[2] = new DPoint3d(3 * UorPerMas, 8 * UorPerMas, 0 * UorPerMas);
    ptArr[3] = new DPoint3d(5 * UorPerMas, 12 * UorPerMas, 0 * UorPerMas);
    ptArr[4] = new DPoint3d(6 * UorPerMas, 10 * UorPerMas, 0 * UorPerMas);
    CurvePrimitive curPri = CurvePrimitive.CreateLineString(ptArr);
    Element ele = DraftingElementSchema.ToElement(dgnModel, curPri, null);
    BIM.Element eleInterop = SampleMixed.ElementOperation.ConvertToInteropEle(ele);
    eleInterop.Color = 3;
    eleInterop.LineWeight = 4;
    ele.AddToModel();
}

 

 

7. Build Solution

 

Under menus, select Build > Build Solution to compile the solution.

 

 

 

    Following element is created and added to active model.

 

    We generated elements through interfaces under the COM framework, then converted

    them into elements under the new programming framework, set their color and line width

    properties, and finally added them to the DGN file. 

 

 

    Following element is created and added to active model.

 

 

You can download the source code for this wiki here.

 

Prev: Calling C/C++ Functions in Add-ins Next: Main Page