C++ DLL Objects accessed from C#

Because there is a few things that c# cannot do compared to c++, e.g. cpu/memory management. And also there is probably allot of dll’s out there are still required for some events, c# is able to communicate with these files and use there functions within the c# language.

To create an dll within Visual Studio 2005 within the language c++, if you do the following

1. New project -> c++ -> empty project
2. Enter project name (e.g. hellocdll)
3. Right click source files ( in the solution explorer) add-> new item
enter an cpp filename.
4, Right click on the main project heading in the solution explorer -> properties
configuration properties->general inner screen project defaults -> configuration type, alter to dynamic library (.dll)
5. Copy and paste code and then compile.

#include <stdio.h>
 
extern "C"
{
  __declspec(dllexport) void DisplayMessageFromDLL()
  {
              printf ("Hi From the C DLL!\n");
  }
 
  __declspec(dllexport) int DisplayValueAndReturn(int i)
  {
         printf("Value %i\n", i);
         return i+2;
  }
}

The extern “C” means that the references within the code are going to be available externally and marco __declsepc(dllexport) is for the MS compile to inform that functions are to be available within an dll file.

To create an c# project to communicate with the above dll

1. New project -> c# -> empty project
2. Enter project name (e.g. hellodlltest)
3. Right click on the project name ( in the solution explorer) add-> new item
select class and enter a filename
4. Copy and paste the code and then compile. (you may need to change the Dllimport to the dll file name that has been created from the c dll project)

using System;
using System.Runtime.InteropServices;     // DLL support
 
namespace hellodlltest
{
    class hellodllC
    {
        [DllImport("hellocdll.dll")]
        public static extern void DisplayMessageFromDLL();
 
        [DllImport("hellocdll.dll")]
        public static extern int DisplayValueAndReturn(int i);
 
        static void Main ()
           {
                  Console.WriteLine ("C# program 'talking' to an C DLL");
            DisplayMessageFromDLL();
            Console.WriteLine(DisplayValueAndReturn(3).ToString());
           Console.ReadLine()
           }
    }
}

5. Copy the dll file from the debug directory of the c++ created dll project and place into the created bin/debug directory for this c# project

Operator

The standard class function are not able to utilize the standard operators within the c# language, for example the multiple, add, subtraction and divide in a mathematics example.

To overcome this problem, there is a ‘operator’ special syntax that allows for this to take place. The operator can work with any of the c# language standard functions of which you are able to program there functional aspects within the class. The syntax for this is

public static <return type> operator <operator type>(<parameter list of passed variables>);

for example if there was an return type of int and two integer values passed in the parameter list and using the addition operator.

public static int operator +(int a, int b)

Below is some code that will demonstrate this further within a general code development.

using System;
 
class operatorBase
{
       private int i;       // private member of the class
 
       public operatorBase() 
       {
              i = 0;       
       }
 
       public operatorBase(int init)  
       {
              this.i = init; 
       }
 
       // get and set the value for the private member i
       public int Value
       {
              get { return i;}
              set { i = value;}
       }
 
       // the operator +, parameters are the two values that you want to add, can be overloaded with different values
       // e.g. (int i2, int i3) for example.
       public static operatorBase operator +(operatorBase i2, operatorBase i3)
       {
              // create the return;
              operatorBase locali= new operatorBase();
              locali.i = i2.i + i3.i;  have access to the internals of passed parameters
              return  locali;       // return the operatorBase class
       }
}
 
class operatorTest
{
 
       public static void Main()
       {
              operatorBase opBase = new operatorBase();
 
              // set the value to 3 and also output the value;
              opBase.Value = 3;
              Console.WriteLine(opBase.Value);
 
              operatorBase opBase2 = new operatorBase(4);
 
              // to add to the operatorbases together, but will return an operatorBase, thus bracket the equation and use the .Value to get the value. 
              Console.WriteLine((opBase + opBase2).Value);
 
              // since creating two new on the fly operatorBase, then the result is an int value again.
              Console.WriteLine((new operatorBase().Value = 3) + (new operatorBase().Value = 2));
       }
}

Yielding results

Yield is a new syntax word within the .net 2 language. This allows for the IEnumerable interface to have direct interaction instead of using the IEnumerator interface to iterate though a result set. For easier demonstration, I think, the code examples, the first code is a .net 1 version of the interface IEnumerable.

using System;
using System.Collections;
 
// the inital class is IEnumerable- means that it has to implement the GetEnumerator
public class Class : IEnumerable 
{
       // internal class to implement the IEnumerator interface, which inturn has to do the MoveNext, Current, Reset methods.
       private class ClassEnumerator : IEnumerator
       {
              // internal values to go through the array
              private int index = -1;
              private Class P;
              // setup the internal variable
              public ClassEnumerator(Class P) 
              {
                     this.P = P; 
              }
              // move within the array, if any values are present.
              public bool MoveNext()
              {
                     index++;
                     return index < P._Names.Length;
              }
              // set the internal to -1, thus restart
              public void Reset() 
              { 
                     index = -1;
              }
 
              // get the Current object
              public object Current 
              { 
                     get 
                     { 
                            return P._Names[index]; 
                     } 
              }
       }
 
       // return a IEnumerator object of the above with itself passed
       public IEnumerator GetEnumerator()
       {
              return new ClassEnumerator(this);
       }
 
       // the internal string array of names
       private string[] _Names;
       // the new class setup process, 
       public Class(params string[] Names)
       {
              _Names = new string[Names.Length];
              // copy the passed parameter starting at position 0
              Names.CopyTo(_Names,0);
       }
}
 
class ClassProgram
{
       static void Main(string[] args)
       {
              Class ClassArr = new Class("Student1", "Student2","Studentx");
              foreach (string s in ClassArr)
                     Console.WriteLine(s);
       }
}

This is able to output a string of

Student1
Student2
Studentx

Since the Class class (it is a class of students), there is allot of code to iterate with the foreach function.

Within .net 2 there is a nice and more tighter method called yield, an yield will yield a result and be able to iterate though a result set with the IEnumerable return set. Again, here is the source code.

using System;
using System.Collections;
 
class yielding
{
       // same as the class as in .net 1 version.
       public class Class : IEnumerable
       {
              // but only need to implement this one method to do the same as the pervious separate class
              public IEnumerator GetEnumerator()
              {
                     int counter = -1;
                     while (counter++ < (_Names.Length-1))
                            yield return _Names[counter];
              }
 
              // same as the other .net 1 class internals for the private variable and the constructor
              private string[] _Names;              
              public Class(params string[] Names)
              {
                     _Names = new string[Names.Length];
                     Names.CopyTo(_Names,0);
              }
       }       
 
       static void Main(string[] args)
       {
              // same as the .net 1 version
              Class ClassArr = new Class("Student1", "Student2", "Studentx");
              foreach (string s in ClassArr)
                     Console.WriteLine(s);
       }
}

Far less code and also the result is exactly the same.

Also there are other benefits of the yield attached to an IEnumerable interface, here is some more code to demonstrate how to implement a power function to display the power result being built up. This demonstrates how to use just a single method to return an iterate-able result.

using System;
using System.Collections;
 
class yielding
{
       // same as the class as in .net 1 version.
       public class Class : IEnumerable
       {
              // but only need to implement this one method to do the same as the pervious separate class
              public IEnumerator GetEnumerator()
              {
                     int counter = -1;
                     while (counter++ < (_Names.Length-1))
                            yield return _Names[counter];
              }
 
              // same as the other .net 1 class internals for the private variable and the constructor
              private string[] _Names;              
              public Class(params string[] Names)
              {
                     _Names = new string[Names.Length];
                     Names.CopyTo(_Names,0);
              }
       }       
 
       // IEnumerable linked to yield is new in .net 2, it allows for the 
       // iteration of this method, acting like array instead of a single return.
       public static IEnumerable Power(int number, int exp)
       {
              int counter = 0, result = 1;       // setup the default values.
              while (counter++ < exp)              // increament counter and whilst lower than the passed parameter exp
              {
                     result *= number;       // result = result * number;
                     yield return result;       // yield the result and return
              }
       }
 
       // can also just iterate though a array of strings (in this example)
       public static IEnumerable StReturn(params string[] names)
       {
              int counter = -1;
              while (counter++ < (names.Length-1))
                     yield return names[counter];
       }
 
       static void Main(string[] args)
       {
              // can do a return of a power function as well
              foreach(int e in Power(4,3))
                     Console.WriteLine(e.ToString());
 
              // you can just iterate a string 
              string[] st = {"student1","student2","studentx"};
              foreach(string s in StReturn(st))
                     Console.WriteLine(s.ToString());
 
              // same as the .net 1 version
              Class ClassArr = new Class("Student1", "Student2", "Studentx");
              foreach (string s in ClassArr)
                     Console.WriteLine(s);
       }
}

I have also include the code from above to demonstrate the similar usage for iterate though a string array.

Output would be

4
16
64
student1
student2
studentx
Student1
Student2
Studentx

You will need to have .net 2 installed or mono (use the gmcs part of mono to use the .net 2 functions.

Generics

A Generic is a way to declassify the type of variable used, e.g. if there was a function to add up two integer values, but you had two double values, then the int function would not function correctly, so there would be a need to function overload the function to allow for the double increment as well. But just envisage that the same function would be required for characters, floats, personally created ones etc, then there would be more functions per type of variable than the actual work done.

A generic class negates this by allowing any class type passed to the function, as long as the type has the standard increment process defined, it will work with any type.

This will demonstrate the basics of the generics.

using System;
 
// create a class with a generic type of T (e.g. pass in the type of your choice
public class GenTest<T>;
{
       // the private value
       private T genericValue;
 
       // default constructor for the class (same name as the class)
       // ~ is the deconstructor
       public GenTest(T generic) 
       {
              genericValue = generic;       // set the internal T = passed value
       }
 
       // return the value of the internal value
       public T ReturnValue()
       {
              return genericValue;
       }
}
 
public class MainProgram
{
       static void Main()
       {
              // create a integer type class, with the default value of 2
              GenTest<int> genInt = new GenTest<int>(2);
              Console.WriteLine("Int generic = " + genInt.ReturnValue());
 
              // same class create a string with the default value of "cool"
              GenTest<string> genString = new GenTest<string>("cool");
              Console.WriteLine("String generic = " + genString.ReturnValue());
       }
}

If you save the code and run with .net 2 or greater (.NET Framework) ( since this was part of .net 2 and not with .net 1). The output will be

Int generic = 2
String generic = cool

As you can see the same class is able to use both integer and strings as the default variable type.

Collections – ArrayList

Collections – ArrayList, the ArrayList is part of the Collections namespace. The ArrayList acts as the same as the array (Array Example) apart from it allows other functional aspects to access the list of array.

Shall comment more on the different aspects in later tutorials, but basically there many different parts to a class that allow for better functionality e.g
1. Interfaces = base of a class for strict implementation)
2. IEnumerable (which is a interface) = means that you implement GetEnumerator aspects of a class, e.g. for the foreach command)
3. Generics (which is part of .net 2) = Similar to templates (Generics) in c++ and also generics from Java).
4. Etc. shall comment more on these.

This is the code

using System;
 
namespace ArrayListTest
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
            arrayList.Add(2);
            arrayList.Add(3);
            arrayList.Add("hi there");
 
            foreach (object obj in arrayList)
                Console.WriteLine(obj.ToString());
        }
    }
}

If you save as arraylisttest.cs, and then run, the output will be

2
3
hi there

It basically allows you to add in any object into the ArrayList, and since objects have the ToString() function, then it is able to print out the object, of course custom made objects will either display there type or the ToString() will have to be implemented.

Arrays

Arrays are ways of having a block of memory allocated to a single variable type, this allows for holding the national lottery numbers within an array of 6 instead of actually having 6 different variables, saves on variable overload

int value1 = new int (1);
int value2 = new int (2);
int value3 = new int (3);
int value4 = new int (4);
int value5 = new int (5);
int value6 = new int (6);

and instead you could just have

int[] values = new int[6] {1,2,3,4,5,6};

This is example code of how to use arrays.

using System;
 
class arrays
{
       public static void Main()
       {
              // the [] means a array declaration, and when you create the new instance of a int you then define the size (3 in this case)
              // if you wish to define the default values, then place these within the {} brackes
              int[] arrayInt = new int[3] { 3,2,1};       
 
              // for each (integer in the array of integers assign to i)
              foreach (int i in arrayInt)
                     Console.WriteLine(i);
 
              // to alter the values within the array, an array always starts at 0
              arrayInt[0] = 20;
              arrayInt[1] = 30;
              arrayInt[2] = 40;
 
              foreach (int i in arrayInt)
                     Console.WriteLine(i);
              return;
       }
}

Save as array.cs and then compile using either mono/csc.exe. The output will be

3
2
1
20
30
40

Method – Add Two numbers

This tutorial uses the same code as Add two numbers but includes a function/method to add two numbers together and return a value. In this case the value is a integer (int) and that is why the int is just before the name of the method (addIntegers) with two parameters passed to the method, these are the values that are being added together. I have called them a and b, so that they are different names to the variables within the main method.

The source code

using System;       // for the console object
 
class addtwonumbers
{
       public static int addIntegers(int a, int b)
       {
              return (a + b);
       }
 
       public static void Main()
       {
              try 
              {
                     // output to the console
                     Console.Write("Please enter value 1 : ");
                     // readin the console input, and then convert to a integer value
                     int val1 = Convert.ToInt32(Console.ReadLine());
                     Console.Write("Please enter value 2 : ");
                     int val2 = Convert.ToInt32(Console.ReadLine());
                     // write out the answer 
                     Console.WriteLine("Answer = " + addIntegers(val1,val2));
              }
              catch (Exception e)
              {
                     // any errors. Like converting a string to a integer value
                     Console.WriteLine("Error : " + e.ToString());
              }
       }
}

save as addtwonumbers_function.cs, this program will function the same as the previous tutorial apart from the inner working will call the method. The method programming allows for one method to be called multiple times, e.g. Within the example above there could be a method that was 5 lines in length and instead of writing the same 5 lines each time, you just write a method that is called.