René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

Creating a dll with MinGW

In MinGW, DLLs are basically created with the -shared option to gcc.
In order to turn the following file into a dll, issue a
gcc -Wall -shared mingw_dll.c -o mingw_dll.dll
I want to create a DLL that exposes one function that takes three parameters. The first is an int. Its value will be printed to stdout. The second parameter is a pointer to a buffer (that is expected to be at least 21 bytes). This buffer will be filled with the string String filled in DLL. The third parameter is actually a pointer to a struct with two elements, an int and a pointer to an array of ints. The int is assumed to be the number of ints in the array. The function will print the ints in the array to stdout.
The function declaration is in a header file:
mingw_dll.h
#ifndef MINGW_DLL_H__
#define MINGW_DLL_H__

struct STRUCT_DLL {
   int  count_int;
   int* ints;
};

int func_dll(
    int                an_int,
    char*              string_filled_in_dll,
    struct STRUCT_DLL* struct_dll
);

#endif
And here's the declaration.
mingw_dll.c
#include <stdio.h>
#include <string.h>

#include "mingw_dll.h"


int func_dll(
    int                an_int,
    char*              string_filled_in_dll,
    struct STRUCT_DLL* struct_dll
) {

  int i;

  printf("\n");
  printf("func_dll called\n");
  printf("---------------\n");
  printf("  an_int=%d\n", an_int);

  strcpy(string_filled_in_dll, "String filled in DLL");

  printf("  count_int=%d: ", struct_dll->count_int);
  for (i=0; i<struct_dll->count_int; i++) {
    printf("  %d", struct_dll->ints[i]);
  }
  printf("\n");


  printf("\nreturning from func_dll\n");
  printf("-----------------------\n\n\n");

  return 2*an_int;
}
This file can be turned into a DLL using the -shared option:
gcc -Wall -shared mingw_dll.c -o mingw_dll.dll

Using the DLL

The follwing c-file uses the DLL:
use_mingw_dll.c
#include <stdio.h>
#include "mingw_dll.h"

int main() {
  char              str[21];
  struct STRUCT_DLL S;
  int               i;

  S.count_int       = 10;
  S.ints            = malloc(sizeof(int) * 10);

  for (i=0; i<10; i++) {
    S.ints[i] = i;
  }


  func_dll(42, str, &S);

  printf("str: %s\n", str);

}
It is compiled like so:
gcc use_mingw_dll.c mingw_dll.dll -o use_mingw_dll
Obviously, the dll can be used like an object (.o) file. The command above creates use_mingw_dll.exe

Calling the DLL from C#