1 Pluspunkt 0 Minuspunkte
Wie kann ich mit MinGW und gcc eine DLL Datei erstellen und mit einem weiteren Programm Funktionen daraus aufrufen?
von  

1 Antwort

2 Pluspunkte 0 Minuspunkte

Zuerst setzt du vor jede Funktionsdefinition das Keyword __declspec(dllimport).

#include <stdio.h>

__declspec(dllimport) int myFunc(int a, float b) {

    printf("%d - %f", a, b);
    return 0;

}

Diese kompilierst du zu einer dynamischen Bibliothek (dll).

gcc -c Lib.c -o Lib.o
gcc -shared Lib.o -o Lib.dll

In deinem Programm musst du die Signatur der jeweiligen Funktion angeben. In diesem Fall ein int als Rückgabe und ein int, ein float als Parameter.

typedef int (__cdecl *MYLIBFUNC)(int, float);

Jetzt lädtst du die Datei und rufst die Funktion auf.

HANDLE dll;
MYLIBFUNC fn; 
    
dll = LoadLibrary("Lib.dll");    
fn = (MYLIBFUNC) GetProcAddress(dll, "myFunc");
    
int i = (*fn)(1, 1.5f);
von (716 Punkte)