How to call C functions from Mathematica using a DLL written in C (or C++)

On this page, I describe how to write a DLL in C (or C++) and call the C functions in that DLL from Excel. This page assumes that you already have a DLL as those described on that page and describes how to call the C functions in the DLL from Mathematica.

Suppose you have the C DLL "squareDLL.dll" with the function "squareForEXL" described on the call a C DLL from Excel page and you want to call it from Mathematica. This can be done with the following lines in Mathematica (this was done in Mathematica 9):

    1. Needs["NETLink`"]

    2. externalSquare = DefineDLLFunction["squareForEXL", "C:\\Users\\Jon\\Documents\\Visual Studio 2008\\Projects\\squareDLL\\x64\\Debug\\squareDLL.dll", "double", {"double[]"}]

      1. The first argument of DefineDLLFunction is the name of the function in the DLL.

      2. The second argument of DefineDLLFunction is the full path and name of the DLL, with the double \\ Mathematica uses for file paths.

      3. The third argument of DefineDLLFunction is the return type returned by the C function.

      4. The fourth argument of DefineDLLFunction is the array of arguments passed to the function. In this case, there's only one argument. That argument is a double array ("double[]") because the C DLL is expecting a reference to a double.

    3. externalSquare[{7.0}]

      1. This calls the C function from the DLL, using the 1x1 double array {7.0}. It returns the double value 49.0

Other notes:

  1. If you wrote the C function to accept a double value instead of reference, you could call the function from Mathematica using a double as an argument (e.g., "externalSquare[7.0]" )

  2. If your C function writes results to an array like the "arrayExcelCDLL.dll" example on the call a C DLL from Excel page :

    1. DefineDLLFunction is used in the same way with the argument that serves as the returned array declared as "double[]"

    2. Create an array to be used as the return array: "returnArray = NETNew["System.Double[]", 7]"

    3. Call the C function using this "returnArray" as that argument

    4. To then use those results in Mathematica, use "NETObjectToExpression[returnArray]"

  3. Note that none of this does anything to deal with memory issues. Look at "NETBlock" and "ReleaseNETObject" for more details.