Home > Articles > Programming > C#

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Inserting the C++ Code into the C# Project

You now have a container project into which you need to drop the C++ code. Listing 2 shows the C++ code. If you’ve already read the command pattern article, this code should be reasonably familiar territory.

Listing 2 C++ implementation of the command pattern.

#region Using directives
using System;
using System.Text;
#endregion

#region Command class
public class Command
{
    public void Execute() {}
    protected Command() {}
}
#endregion

#region Connection class
public unsafe class Connection
{
    public Connection() {}
    private char* Path; // "Unsafe" code
    int resourceId;
}
#endregion

#region LspConnection class

public class LspConnection : Connection
{
public LspConnection(int Id, int lspPreference, int lspPathId)
{
    Console.WriteLine("Creating an LSP\n");
    lspId = Id;
    preference = lspPreference;
    pathId = lspPathId;
}

private int lspId;
private int preference;
private int pathId;    
public int getLspId() { return lspId; }
public int getLspPreference() { return preference; }
public int getLspPathId() { return pathId; }
};

#endregion

#region deleteNetworkObject class
public class deleteNetworkObject : Command
{
public deleteNetworkObject(LspConnection lsp)
{
    connection = lsp;
}

public void Execute()
{
//Delete the LSP components starting with the LSP
Console.WriteLine("Deleting LSP ID {0}: ", connection.getLspId());

//Delete the LSP preference
Console.WriteLine("Deleting LSP Preference {0}", connection.getLspPreference());

//Delete the LSP path ID
Console.WriteLine("Deleting LSP Path ID {0}", connection.getLspPathId());
}

private LspConnection connection;
}

#endregion
}

One item of interest in Listing 2 is the Connection class. This class contains a pointer called Path. While this usage is standard in C++, this code is deemed to be unsafe by C#, so it must be marked as unsafe. This is why the class name is as follows:

public unsafe class Connection

Listing 3 is the code from main.cs; you can see where we actually call the code from Listing 2.

Listing 3 Calling the ported C++ code from C#.

using System;
using System.Collections.Generic;

namespace MigrateC__ToC_
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
LspConnection lsp = new LspConnection(1, 0, 1);
deleteNetworkObject deleteObject =
 new deleteNetworkObject(lsp);
deleteObject.Execute();

Console.ReadLine();
}
}

That’s all the code we’ll be porting. Remember, the command pattern is very powerful and extremely concise. If you try to compile the project now, you’ll get warnings about the use of unsafe code, so we need some rules for the next stage in the code migration.

  • + Share This
  • 🔖 Save To Your Account