05. Dynamic link library

1. Providing your own dynamic-link library

To create a dynamic-link library (DLL) from a .NET project, you can follow these steps:

  1. Open a command prompt or terminal window and navigate to the directory where you want to create your project.

  2. Run dotnet new console --language C# to create a new .NET console project in C#, or dotnet new console --language F# to create a project in F#.

  3. Open the project in your preferred code editor or IDE.

  4. By default, dotnet new console creates a Program file with the extension of the chosen programming language. In this file, you can create a namespace, class, and methods for use with pldotnet, as shown in the following example:

    namespace TestDLLFunctions
    {
        public class TestClass
        {
            public static BitArray? modifybit(BitArray? a)
            {
                if (a == null)
                {
                    return null;
                }
    
                a[0] = !a[0];
                a[^1] = !a[^1];
                return a;
            }
        }
    }
    
  5. Build the project using the dotnet build . -c Release command.

  6. If the build is successful, you will find the DLL file in the bin folder of your project.

You can then use the DLL file in other .NET projects by adding a reference to it in your project and calling the function from your code.

To run the DLL inside SQL, connect to the database using a tool such as psql or a graphical client.

Create a function in the database that maps to the DLL function you want to use.

The path to the DLL file and the fully-qualified name of the function (including the namespace and class name) are specified in the AS clause.

Here is how it is composed:

path/to/file/filename.dll:NamespaceName.ClassName!FunctionName

In the example you bellow, the function is named modifyBitDLL and takes a single argument of type BIT(10). The function is defined using the CREATE OR REPLACE FUNCTION statement:

CREATE OR REPLACE FUNCTION modifyBitDLL(a BIT(10)) RETURNS BIT(10) AS '/app/pldotnet/tests/csharp/DotNetTestProject/bin/Release/net6.0/CSharpTest.dll:TestDLLFunctions.TestClass!modifybit' LANGUAGE plcsharp;

After creating the function, you can call it like any other function in the database using the SELECT statement.

In the example, the function is called with the argument '10101'::BIT(10) in the code below:

SELECT modifyBitDLL('10101'::BIT(10));

The output of the function will depend on the specific logic implemented in the DLL function.

The output in this case is the modified BIT(10) value returned by the DLL function:

 modifybitdll
--------------
 0010100001
(1 row)